[英]MongoDB aggregation get last element's field from nested array
我想只聚合和显示嵌套数组中的最后一个 object 这是我的数据库:
[{
"firstName": "Shaun",
"salary": [
{
"id":1,
"rate": 250,
},
{
"id":2,
"rate": 290,
}
]
},{
"firstName": "Julian",
"salary": [
{
"id":1,
"rate": 750,
},
{
"id":2,
"rate": 760,
},
{
"id":3,
"rate": 790,
},
]
}
}]
我想要的结果是:
{"firstName": "Shaun", "rate":290},{"firstName": "Julian", "rate":790}
试试下面的聚合查询,它使用$arrayElemAt salary.rate
数组薪水中获取最后一个元素:
db.collection.aggregate({
$project: {
firstName: 1,
rate: { $arrayElemAt: [ "$salary.rate", -1 ] }
}
})
测试: mongoplayground
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.