Brandon
Brandon

Reputation: 2125

Any way to group Mongodb query result by column?

Pretty new to Mongodb and I am trying to construct a query using Mongoose to get a desired result, if possible.

Test data:

{ id: 1, display_time: '01:00', name: 'test1' },
{ id: 2, display_time: '03:00', name: 'test2' },
{ id: 3, display_time: '01:00', name: 'test3' },
{ id: 4, display_time: '04:00', name: 'test4' },
{ id: 5, display_time: '01:00', name: 'test5' }

Desired result:

{
  "01:00": [
     { id: 1, display_time: '01:00', name: 'test1' },
     { id: 3, display_time: '01:00', name: 'test3' },
     { id: 5, display_time: '01:00', name: 'test5' }
  ],
  "03:00": [
     { id: 2, display_time: '03:00', name: 'test2' }
  ],
  "04:00": [
     { id: 4, display_time: '04:00', name: 'test4' }
  ],
}

Basically it groups the documents based on the display_time field and returns it in that format. Is this possible with Mongo?

Upvotes: 0

Views: 51

Answers (1)

siavolt
siavolt

Reputation: 7077

You can try somthing like this:

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

 {
  "_id" : "01:00",
  "test" :
     [
         { id: 1, display_time: '01:00', name: 'test1' },
         { id: 3, display_time: '01:00', name: 'test3' }
     ]
}

{
  "_id" : "04:00",
  "test" :
     [
       { id: 4, display_time: '04:00', name: 'test4' }
     ]
}

For moar information http://docs.mongodb.org/manual/reference/operator/aggregation/group/

Upvotes: 1

Related Questions