我在MongoDB中有一些数据存储:
{
"_id" : ObjectId("52983ff67dbf497a8bb0192b"),
"data" : [
{
"LoadPct" : 10,
"RECORD_SEQ" : 1
}
]
}
{
"_id" : ObjectId("5298400b7dbf497a8bb0192d"),
"data" : [
{
"LoadPct" : 59,
"RECORD_SEQ" : 2
}
]
}
{
"_id" : ObjectId("529840217dbf497a8bb01934"),
"data" : [
{
"LoadPct" : 8,
"RECORD_SEQ" : 3
}
]
}
现在我希望查询将返回具有自定义格式的数据,例如
_id LoadPct
ObjectId("52983ff67dbf497a8bb0192b") 10
ObjectId("5298400b7dbf497a8bb0192d") 59
ObjectId("529840217dbf497a8bb01934") 8
这可能吗?
//更新:我尝试使用Aggregate但错误确认:
> db.data.aggregate( {$match:{'data.LoadPct':{$gt:5}}}, {$group:{'_id':"_id",'data':'data.LoadPct'}} )
Error: Printing Stack Trace
at printStackTrace (src/mongo/shell/utils.js:37:15)
at DBCollection.aggregate (src/mongo/shell/collection.js:897:9)
at (shell):1:24
Mon Dec 16 14:44:27.208 JavaScript execution failed: aggregate failed: {
"errmsg" : "exception: the group aggregate field 'data' must be defined as an expression inside an object",
"code" : 15951,
"ok" : 0
} at src/mongo/shell/collection.js:L898
怎么了?
答案 0 :(得分:1)
您需要使用聚合查询和$ unwind管道。 Check MongoDB documentation
答案 1 :(得分:1)
您确定需要汇总吗?它看起来像一个简单的查找将返回您想要的数据,但不完全相同的形状:
db.data.find( {"data.LoadPct" : {"$gt" : 10}}, {"data.LoadPct" : 1} )
顺便说一句,“数据”真的是一个包含两个键:值对的文档数组吗?在汇总的示例代码中,我认为您忘记了要求字段值的$。
您看到的错误消息表示您要求mongodb按字段'data'聚合,但未指定聚合它的操作。
将它与SQL中的以下内容进行比较:
# select a, b from foo group by a;
ERROR: column "foo.b" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: select a, b from foo group by a;
相反:
# select a, max(b) from foo group by a;
a | max
----+-----
bb | 7
aa | 9
这就是你所要求的:
query = [
{"$match":{"data.LoadPct":{"$gt":5}}},
{"$unwind":"$data"},
{"$project" : {"data" : "$data.LoadPct"}},
{"$group" : {"_id" : "$_id", "data" : {"$first" : "$data"}}}
]
db.data.aggregate(query)