1

How can I query on the nth element of a subdocument array in MongoDB where n is variable?

Suppose, I've documents like bellow:

{
  list:[
    {
      a: true,
      b: 'abc'
    },
    {
      a: false,
      b: 'def'
    },
    {
      a: true,
      b: 'ghi'
    },
  ]
}
  1. Query 1: I need to find all documents which have a: false on the 1st element of list(i.e. 'list.0.a': false)

  2. Query 2: I need to find all documents which have a: false on the 2nd element of list(i.e. 'list.1.a': false)

  3. Query 3: I need to find all documents which have a: false on the 3rd element of list(i.e. 'list.2.a': false)

3
  • What have tried so far? Commented Aug 21, 2019 at 23:23
  • Why not just run query like db.collection.find({ "list.1.a": false}) Commented Aug 22, 2019 at 5:14
  • 1
    @Caconde I tried deconstructing array with unwind but it doesn't help. @mickl 's answer works perfectly! Commented Aug 22, 2019 at 6:28

1 Answer 1

2

You can use $expr to use aggregation expressions in your query, $let to define temporary variable, $arrayElemAt to take nth element of an array:

db.collection.find({
    $expr: {
        $let: {
            vars: { fst: { $arrayElemAt: [ "$list", 0 ] } },
            in: { $eq: [ "$$fst.a", false ] }
        }
    }
})
Sign up to request clarification or add additional context in comments.

2 Comments

This works perfectly! Thanks! Anyway, is there any performance issue with $expr operator?
@MostafizRahman I don't think so - it's just because there are two types of operators: the old ones for querying and the new ones from aggregation so it's a kind of bridge between these two worlds

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.