'Found value in array under sub folder in mongodb

I have this document in mongoDb:

    {
        "_id" : ObjectId("zzzzzz"),
        "createdAt" : ISODate("2020-07-07T11:45:29.517Z"),
        "updatedAt" : ISODate("2020-07-07T11:45:29.517Z"),
        "merchantLenderContracts" : [ 
            [ 
                ObjectId("22222")
            ]
        ],
        "merchantId" : ObjectId("111111"),
        "__v" : 0
    }

I want to catch the value: ObjectId("22222") under array 0 by mongodb query.

Can anyone help me?

enter image description here



Solution 1:[1]

Assuming you are matching by the first object in the array being 22222, you can perform the query by using index 0.

db.collection.find({
  "merchantLenderContracts.0.0": "22222"
})

Here is the Mongo playground for your reference.

For a more generic way for searching(i.e. without specific index in array), we may use $reduce to flatten the nested array for searching.

db.collection.aggregate([
  {
    "$match": {
      $expr: {
        "$in": [
          "22222",
          {
            "$reduce": {
              "input": "$merchantLenderContracts",
              "initialValue": [],
              "in": {
                "$concatArrays": [
                  "$$value",
                  "$$this"
                ]
              }
            }
          }
        ]
      }
    }
  }
])

Here is the Mongo playground for your reference.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1