如何使用MongoDB查询语言提取对象数组最后一个元素的指定字段值
方案1:通用聚合查询(兼容MongoDB 3.2及以上所有版本)
直接使用$arrayElemAt操作符,传入索引-1即可获取数组最后一个元素,再提取对应qty字段:
db.offer.aggregate([ { $match: { _id: ObjectId("614513461af3bf569fdc420e") } }, { $project: { _id: 0, lastInstockQty: { $let: { vars: { lastItem: { $arrayElemAt: [ "$instock", -1 ] } }, in: "$$lastItem.qty" } } } } ])
执行返回结果如下:
{ "lastInstockQty" : 35 }
如果使用MongoDB 5.0及以上版本,可以用更简洁的$getField代替$let写法:
db.offer.aggregate([ { $match: { _id: ObjectId("614513461af3bf569fdc420e") } }, { $project: { _id: 0, lastInstockQty: { $getField: { field: "qty", input: { $arrayElemAt: [ "$instock", -1 ] } } } } } ])
方案2:普通find查询(仅兼容MongoDB 4.4及以上版本)
4.4版本开始支持在find的投影参数中使用聚合表达式,写法更简单:
db.offer.find( { _id: ObjectId("614513461af3bf569fdc420e") }, { _id: 0, lastInstockQty: { $getField: { field: "qty", input: { $arrayElemAt: [ "$instock", -1 ] } } } } )
如果需要直接拿到数值本身,不需要外层的对象包裹,可以在查询末尾追加.next().lastInstockQty:
const targetQty = db.offer.aggregate([ { $match: { _id: ObjectId("614513461af3bf569fdc420e") } }, { $project: { _id: 0, lastInstockQty: { $getField: { field: "qty", input: { $arrayElemAt: [ "$instock", -1 ] } } } } ]).next().lastInstockQty // targetQty的值为35
内容的提问来源于stack exchange,提问作者Wrapper
相关产品推荐
相关产品推荐

