拥有以下数据
{
"_id": "...",
"name": "John",
"purchases": [
{
"date": {
"$date": "2016-12-20T00:00:00.000Z"
},
"amount": 1000
},
{
"date": {
"$date": "2016-12-23T00:00:00.000Z"
},
"amount": 100
}
]
}
如何获取具有不同名称的结果字段的最新购买金额?
获得下一个结果:
{
"_id": "...",
"name": "John",
"purchases": [
{
"date": {
"$date": "2016-12-20T00:00:00.000Z"
},
"amount": 1000
},
{
"date": {
"$date": "2016-12-23T00:00:00.000Z"
},
"amount": 100
}
]
},
"latestPurchaseAmount": 100
}
答案 0 :(得分:1)
答案 1 :(得分:1)
你可以这样做。以下查询将展开集合中的所有购买,并按日期降序对购买进行排序,并将结果限制为1并投影相应的金额。
db.purchases.aggregate([{
$unwind: "$purchases"
}, {
$sort: {
"purchases.date": -1
}
}, {
$limit: 1
}, {
$project: {
_id: 0,
latestPurchaseAmount: "$purchases.amount"
}
}]);
输出
{ "latestPurchaseAmount" : 100 }