Basten Gao
Basten Gao

Reputation: 298

How to use elemMatch to match nested array

I have some data structure like this

{
  a: 1,
  array1: [
    {
      b: 2
      array2: [
        { 
          // this is my target
          c: 3,
          d: 3
        },
        {
          c: 4,
          d: 4
        }          
      ]
    },
    {
      b: 3
      array2: [
        {
          c: 5,
          d: 5
        },
        {
          c: 6,
          d: 6
        }          
      ]
    }
  ]
}

I know use {"array1" : {"$elemMatch" : {"b" : 2} } } to match element of first level array1. But I don't know how to match element {c: 3, d: 3} of array2 of array1.

Upvotes: 15

Views: 17538

Answers (3)

Rafiq
Rafiq

Reputation: 11445

let feed = await Doc.findOneAndUpdate(
      {
        $and: [
          {
            _id: req.params.id,
          },
          {
            'feeds.$[].locations': {
              $elemMatch: {
                uniqueName,
              },
            },
          },
        ],
      },
      {
        $pull: {
          //@ts-ignore
          'feeds.$[].locations': { uniqueName },
        },
      },
      { new: true }
    );

Upvotes: 0

Rahul
Rahul

Reputation: 16335

$elemMatch is used to state association among multiple fields within the same nested structure.

For eg. If you are looking to query c and d and need them to belong to the same sub-document, the you can query it like.

{"array1.array2" : {"$elemMatch" : {"c" : 3, "d":3} } } 

Note: if you are querying on a single field, you dont really need to use $elemMatch (since there is no association)

For instance, in your query example, you can instead do

{"array1.b" : 2} 

Upvotes: 20

hi54yt
hi54yt

Reputation: 111

try this,it help me a lot.

{ 
  "array1": {
    "$elemMatch": {
      "array2": {
        "$elemMatch": {
          "c": 3
        }
      }
    }
  }
}

Upvotes: 11

Related Questions