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

Viewed 41

I'm new to Mongo. By new I mean couple of hours new.

Basically I have this document structure:

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

I would like if possible to extract particular field (i.e. its value) from instock's last element. In this case I just need to extract 35 i.e. qty field.

I have managed to do this:

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

Which results in :

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

I don't know how to reach to last object in array and than its qty field and everything needs to be as single query.

1 Answers

Aggregate solution
(requires MongoDB 5, else query would be a little bigger)

Query

  • filter for the _id with the $match stage
  • get last element of $instock, and then field qty
  • project to keep only the above part

*we do it like we would do it in a programming language, get last element, and get a field value.

Test code here

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