1

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 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

For more curiosity , Can i reduce last pipeline?
What do you mean?
i think he wants to eliminate(remove) {$project: {indexValue: "$item.z"}} this pipeline
Sure you can, but it will not give you the result you asked for. The playground example in the answer, allows to look at the pipeline results step-by-step, to better understand the pipeline. Look for the drop-down with the steps list

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.