I have a collection of objects in MongoDB that looks like this
{ "event_type": "event1", "created_at": some_date, ...more_fields... },
{ "event_type": "event2", "created_at": some_date, ...other_fields... },
{ "event_type": "event1", "created_at": some_date, ...more_fields... }
Now I want to have the above data with all fields grouped by some field (which might not be present in all objects) and order it by the highest created_at date. I have tried to do this using the Aggregation Framework with the following query:
collection.aggregate([
{ "$group" => {
:_id => "$somefield",
:last_time => { "$max" => "$created_at" },
:events => { "$push" => { ... } }
}
},
{ "$match" => { "_id" => { "$ne" => nil } } },
{ "$sort" => { "last_time" => -1 } }
])
The problem I'm facing is related to the line
:events => { "$push" => { ... } }
If I put in some specific fields then it works, but I don't know which exact fields the collection contains. But rather I want the whole object returned like this:
{
"event_type": "event1", "last_time": some_date, "events": [
{ "event_type": "event1", "created_at": some_date, ...more_fields... },
{ "event_type": "event1", "created_at": some_date, ...more_fields... },
...
]
}