gpt4 book ai didi

MongoDb:使用 Groovy 语言进行聚合

转载 作者:IT老高 更新时间:2023-10-28 13:30:04 26 4
gpt4 key购买 nike

我在 SpagoBI 下使用 groovy 脚本。我想使用聚合。例如,我想执行以下聚合:

db.myCollection.aggregate(
[
{
$group : {
_id : { day: { $dayOfMonth: "$recvTime" } }

}
}
]
)

我试过了:

DBObject projectFields = new BasicDBObject('$dayOfMonth',"recvTime");
DBObject project=new BasicDBObject('$project',projectFields)

DBObject groupFields = new BasicDBObject( "_id",project);

DBObject group = new BasicDBObject('$group', groupFields);

iterable = db.getCollection('myCollection').aggregate(group)

我收到了这个错误:

An unexpected error occured while executing dataset: { "serverUsed" : "192.168.1.160:27017" , "errmsg" : "exception: invalid operator '$project'" , "code" : 15999 , "ok" : 0.0}

有什么想法吗?

更新:在 Mongo shell 中执行的查询

db['cygnus_/kurapath_enocean_power_enocean'].aggregate(
... [
... {
... $group : {
... _id : { day: { $dayOfMonth: "$recvTime" } }
... }
... }
... ]
... );
{ "_id" : { "day" : 9 } }
{ "_id" : { "day" : 8 } }
{ "_id" : { "day" : 7 } }
{ "_id" : { "day" : 4 } }
{ "_id" : { "day" : 3 } }

存储在 mongo db 中的数据:

db['cygnus_/kurapath_enocean_power_enocean'].find()
{ "_id" : ObjectId("55e81e9631d7791085668331"), "recvTime" : ISODate("2015-09-03T10:19:02Z"), "attrName" : "power", "attrType" : "string", "attrValue" : "2085.0" }
{ "_id" : ObjectId("55e81e9631d7791085668332"), "recvTime" : ISODate("2015-09-03T10:19:02Z"), "attrName" : "power", "attrType" : "string", "attrValue" : "2085.0" }
{ "_id" : ObjectId("55e81e9831d7791085668333"), "recvTime" : ISODate("2015-09-03T10:19:04Z"), "attrName" : "power", "attrType" : "string", "attrValue" : "2077.0" }

最佳答案

根据错误,聚合不需要 $project 运算符,因此您应该更改 projectFieldsproject 变量来显示实际的管道表达式,即

DBObject dateFields = new BasicDBObject("$dayOfMonth", "$recvTime");
DBObject dateObject = new BasicDBObject("day", dateFields);

DBObject groupFields = new BasicDBObject( "_id", dateObject);
DBObject group = new BasicDBObject('$group', groupFields);

iterable = db.getCollection('myCollection').aggregate(group);

关于MongoDb:使用 Groovy 语言进行聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32459956/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com