是否可以查询MongoDB文档并将其分组到子文档数组中?

时间:2017-02-16 17:41:42

标签: mongodb mongodb-query aggregation-framework

我有以下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查询(可能是聚合)来实现?

1 个答案:

答案 0 :(得分:1)

您可以尝试以下内容。

db.collection.aggregate(
    [{
        $group: {
            _id: "$stamp_dt",
            "data": {
                $push: {
                    _id: "$_id",
                    start_lat: "$start_lat",
                    asimId: "$asimId"
                }
            }
        }
    }]
)

如果您不介意数组中的stamp_dt,可以将查询简化为

db.collection.aggregate(
    [{
        $group: {
            _id: "$stamp_dt",
            "data": {
                $push: "$$ROOT"
            }
        }
    }]
)