我想使用聚合函数获取每个城市最后时间戳的“人口”。
在这样的 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}
]
}
我尝试过类似this answer的东西,但我不知道在获取每个城市的最新时间戳后如何“放松”人口:
db.collection('population').aggregate([
{ $unwind: '$population' },
{ $group: { _id: '$city', timestamp: { $max: '$timestamp' } } },
{ $sort: { _id : -1 } }
], function(err, results) {
res.send(results)
});
最佳答案
以下聚合管道将为您提供所需的结果。管道中的第一步按 timestamp
字段(降序)对文档进行排序,然后按下一个 $group
中的 city
字段对排序后的文档进行分组。阶段。 $group
内运算符,您可以通过 $$ROOT
提取 population
数组字段运算符(operator)。 $first
运算符返回应用 $$ROOT
得到的值表达式指向共享相同 city
键的一组文档中的第一个文档。最后的管道阶段涉及将前一个管道中的字段投影到所需的字段中:
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
}
关于node.js - 按最新时间戳聚合 mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29772575/