使用 mongodb 查询语言从对象数组中提取最后一个值?

Extract last value from an array of objects using monogdb query language?

我是 Mongo 的新手。新的我的意思是几个小时的新。

基本上我有这样的文档结构:

{     
      _id: ObjectId("614513461af3bf569fdc420e"),
      item: 'postcard',
      status: 'A',
      size: { h: 10, w: 15.25, uom: 'cm' },
      instock: [ { warehouse: 'B', qty: 15 }, { warehouse: 'C', qty: 35 } ] 
}

如果可能的话,我想从 instock 的最后一个元素中提取特定字段(即它的值)。在这种情况下,我只需要提取 35qty 字段。

我做到了:

db.offer.find( { _id: ObjectId("614513461af3bf569fdc420e") }, { instock: 1, _id: 0} )

这导致:

{ instock: [ { warehouse: 'B', qty: 15 }, { warehouse: 'C', qty: 35 } ] }

我不知道如何到达数组中的最后一个对象及其 qty 字段,所有内容都需要作为单个查询。

聚合解
(需要 MongoDB 5,否则查询会大一点)

查询

  • _id 阶段$match 的过滤器
  • 获取 $instock 的最后一个元素,然后获取字段 qty
  • 项目只保留以上部分

*我们像在编程语言中那样做,获取最后一个元素,并获取字段值。

Test code here

db.collection.aggregate([
{"$match": {"_id": ObjectId("614513461af3bf569fdc420e")}},
{
  "$project": {
  "_id": 0,
  "qty": {"$getField": {"field": "qty","input": {"$last": "$instock"}}}
  }
}
])