15

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.

Basten Gao
  • 198
  • 1
  • 1
  • 10
  • Meaning what exactly? This is easily misinterpretted. Are you just trying to match your document macted on `"array1.array2.c": 3`? ( big hint ). Or are you expecting projection of only matched elements? This looks dangerously abstract in a way that you are likely to misinterpret the answer into your real data. – Blakes Seven Mar 23 '16 at 01:48
  • Actually I want to match that element and project it. – Basten Gao Mar 23 '16 at 01:55
  • Like I said, *"Meaning What?"* given the above query expression which I gave you ( which is all you really need here, and **not** `$elemMatch` ), then what do you expect to return? If you expect **only** `c: 3` and **not** `c: 4` then that makes a **big** difference to the answer to the question. – Blakes Seven Mar 23 '16 at 01:59

3 Answers3

20

$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} 
Rahul
  • 15,979
  • 4
  • 42
  • 63
11

try this,it help me a lot.

{ 
  "array1": {
    "$elemMatch": {
      "array2": {
        "$elemMatch": {
          "c": 3
        }
      }
    }
  }
}
hi54yt
  • 111
  • 4
0
let feed = await Doc.findOneAndUpdate(
      {
        $and: [
          {
            _id: req.params.id,
          },
          {
            'feeds.$[].locations': {
              $elemMatch: {
                uniqueName,
              },
            },
          },
        ],
      },
      {
        $pull: {
          //@ts-ignore
          'feeds.$[].locations': { uniqueName },
        },
      },
      { new: true }
    );
Rafiq
  • 8,987
  • 4
  • 35
  • 35