Chad Johnson
Chad Johnson

Reputation: 21895

Is it possible to query and group MongoDB documents into a subdocument array?

I have the following MongoDB documents:

{ 
    "_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")
}

Notice that all have the same value for stamp_dt. I need a way to group these documents like this:

{
    "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")
        }
    ]
}

I could do this using code, but is there a way to do so via a MongoDB query (perhaps aggregation)?

Upvotes: 0

Views: 27

Answers (1)

s7vr
s7vr

Reputation: 75914

You can try something like below.

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

and if you don't mind the stamp_dt in the array you can simplify the query to

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

Upvotes: 1

Related Questions