0
我有以下MongoDB的文件:是否可以查询MongoDB文档并将其分组到一个子文档数组中?
{
"_id" : ObjectId("58950c9c247430c8d9f3997c"),
"stamp_dt" : ISODate("2015-10-15T00:09:00.000+0000"),
"start_lat" : 52.49512579479001,
"asimId" : ObjectId("588fbe3b835262b7f5ede6f5")
}
{
"_id" : ObjectId("58950c9c247430c8d9f3997d"),
"stamp_dt" : ISODate("2015-10-15T00:09:00.000+0000"),
"start_lat" : 52.48510698285751,
"asimId" : ObjectId("588fbe3b835262b7f5ede6f5")
}
{
"_id" : ObjectId("58950c9c247430c8d9f3997e"),
"stamp_dt" : ISODate("2015-10-15T00:09:00.000+0000"),
"start_lat" : 52.49966542235,
"asimId" : ObjectId("588fbe3b835262b7f5ede6f5")
}
{
"_id" : ObjectId("58950c9c247430c8d9f3997f"),
"stamp_dt" : ISODate("2015-10-15T00:09:00.000+0000"),
"start_lat" : 52.52645820975653,
"asimId" : ObjectId("588fbe3b835262b7f5ede6f5")
}
注意,都对stamp_dt
相同的值。我需要一种方法来组这些文件是这样的:
{
"stamp_dt" : ISODate("2015-10-15T00:09:00.000+0000"),
"results": [
{
"_id" : ObjectId("58950c9c247430c8d9f3997c"),
"start_lat" : 52.49512579479001,
"asimId" : ObjectId("588fbe3b835262b7f5ede6f5")
}
{
"_id" : ObjectId("58950c9c247430c8d9f3997d"),
"start_lat" : 52.48510698285751,
"asimId" : ObjectId("588fbe3b835262b7f5ede6f5")
}
{
"_id" : ObjectId("58950c9c247430c8d9f3997e"),
"start_lat" : 52.49966542235,
"asimId" : ObjectId("588fbe3b835262b7f5ede6f5")
}
{
"_id" : ObjectId("58950c9c247430c8d9f3997f"),
"start_lat" : 52.52645820975653,
"asimId" : ObjectId("588fbe3b835262b7f5ede6f5")
}
]
}
我可以使用代码做到这一点,但有没有办法通过MongoDB的查询(也许聚集)这样做呢?
你可以尝试这样的事情。 'db.collection.aggregate( \t [{ \t \t $组:{ \t \t \t _id: “$ stamp_dt”, \t \t \t “结果”:{ \t \t \t \t $推:{ \t \t \t \t \t _id: “$ _id”, \t \t \t \t \t start_lat: “$ start_lat” \t \t \t \t \t asimId = “$ asimId” \t \t \t \t} \t \t \t} \t \t} \t}] )' – Veeram
谢谢!这工作。如果您想将其作为答案发布,我会将其标记为答案并给予您信任。 –