按最新的时间戳聚合mongodb

我想使用聚合函数得到每个城市上次时间戳的“人口”。

在这样的MongoDB中:

{ "_id": {"$oid": "55354bc97b5dfd021f2be661"}, "timestamp": {"$date": "2015-04-20T18:56:09.000Z"}, "city": "Roma", "population": [ {"age": 90,"count": 1000}, {"age": 25,"count": 25} ] }, { "_id": {"$oid": "55354c357b5dfd021f2be663"}, "timestamp": {"$date": "2015-04-20T18:57:57.000Z"}, "city": "Madrid", "population": [ {"age": 90,"count": 10}, {"age": 75,"count": 2343}, {"age": 50,"count": 500}, {"age": 70,"count": 5000} ] }, { "_id": {"$oid": "55362da541c37aef07d4ea9a"}, "timestamp": {"$date": "2015-04-21T10:59:49.000Z"}, "city": "Roma", "population": [ {"age": 90,"count": 5} ] } 

我想检索所有的城市,但每个只有最新的时间戳:

 { "city": "Roma", "population": [ {"age": 90,"count": 5} ] }, { "city": "Madrid", "population": [ {"age": 90,"count": 10}, {"age": 75,"count": 2343}, {"age": 50,"count": 500}, {"age": 70,"count": 5000} ] } 

我已经尝试了这样的答案 ,但是我不知道如何在获得每个城市的最新时间戳后“放松”人口:

 db.collection('population').aggregate([ { $unwind: '$population' }, { $group: { _id: '$city', timestamp: { $max: '$timestamp' } } }, { $sort: { _id : -1 } } ], function(err, results) { res.send(results) }); 

下面的聚合pipe道会给你想要的结果。 stream水线中的第一步是按timestamp字段(降序)对文档进行sorting,然后在下一个$group阶段将sorting的文档按city字段进行$group 。 在$group操作符中,可以通过$$ROOT操作符来提取population数组字段。 $first操作符返回将$$ROOTexpression式应用于共享同一个city关键字的一组文档中的第一个文档的结果。 最后的stream水线阶段涉及将前一个stream水线的字段投影到所需的字段中:

 db.population.aggregate([ { "$sort": { "timestamp": -1 } }, { "$group": { "_id": "$city", "doc": { "$first": "$$ROOT" } } }, { "$project": { "_id": 0, "city": "$_id", "population": "$doc.population" } } ]); 

输出

 /* 0 */ { "result" : [ { "city" : "Madrid", "population" : [ { "age" : 90, "count" : 10 }, { "age" : 75, "count" : 2343 }, { "age" : 50, "count" : 500 }, { "age" : 70, "count" : 5000 } ] }, { "city" : "Roma", "population" : [ { "age" : 90, "count" : 5 } ] } ], "ok" : 1 } 

我认为你想要使用$project而不是$unwind

 db.collection('population').aggregate([{ $group: { _id: '$city', timestamp: {$max: '$timestamp'} } }, { $project: { population: '$doc.population' } }, { $sort: { _id : -1 } }], function(err, results) { res.send(results) });