我在 MongoDB 中有一组看起来像这样的对象
{ "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... }
现在,我希望将所有字段的上述数据按某个字段(可能并不存在于所有对象中)分组,并按最高 created_at 日期对其进行排序。我尝试使用带有以下查询的聚合框架来执行此操作:
collection.aggregate([
{ "$group" => {
:_id => "$somefield",
:last_time => { "$max" => "$created_at" },
:events => { "$push" => { ... } }
}
},
{ "$match" => { "_id" => { "$ne" => nil } } },
{ "$sort" => { "last_time" => -1 } }
])
我面临的问题与线路有关
:events => { "$push" => { ... } }
如果我输入一些特定的字段,那么它会起作用,但我不知道该集合包含哪些确切的字段。但我希望整个对象像这样返回:
{
"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... },
...
]
}