MongoDB aggregate value of key at array where index is given

Viewed 27

get value from items.z where y=five

Sample data

 [
 {
 "_id": 1,
 "items": [
   {
     x: "one",
     y: "two",
     z: "three"
   },
   {
     x: "four",
     y: "five",
     z: "six"
   }
 ]
 }]

Expected result

 [{
 "_id": 1,
 "indexValue": "six"
  }]

Tried query

db.collection.aggregate([
{
 $match: {
   _id: 1
 }
},
{
 $project: {
   indexValue: {
     $arrayElemAt: [
       "$items",
       1
     ]
   }
 }
},
{
 $project: {
   indexValue: "$indexValue.z"
 }
}
 ])

Here i dont know index and it take 2 pipelines

So how to get that value and can do it in one pipeline because of performance issue?

1 Answers

One option is to use $filter:

db.collection.aggregate([
  {$match: {_id: 1}},
  {$project: {
      item: {
        $first: {
          $filter: {
            input: "$items",
            cond: {$eq: ["$$this.y", "five"]}
          }
        }
      }
    }
  },
  {$project: {indexValue: "$item.z"}}
])

See how it works on the playground example

Related