Query a nested array in mongo with qualifiers

Viewed 42
arr :  [
    [a,b],
    [c,d],
    [g,i]
]

I want to query the above array in such manner where each array in the root array acts as the following logic: include A or B and C or D and G and I

Basically, each nested array acts as a AND qualifier and the items within that nested array act as an OR qualifier

Update the object inside the nested array would look like this:

{
  "foo":{ "$oid":"615469ac6187ab0c8613b7b6"},
  "score":25,        
}

And I would specify the ids of the objects that I want it to match in the nested arrays

1 Answers

Query

  • reduce starting from true
  • each step is like (and $$value (or member1 member2))

Test code here

db.collection.aggregate([
  {
    "$match": {
      "$expr": {
        "$reduce": {
          "input": "$arr",
          "initialValue": true,
          "in": {
            "$and": [
              "$$value",
              {
                "$or": [
                  {
                    "$arrayElemAt": [
                      "$$this",
                      0
                    ]
                  },
                  {
                    "$arrayElemAt": [
                      "$$this",
                      1
                    ]
                  }
                ]
              }
            ]
          }
        }
      }
    }
  }
])
Related