Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use elemMatch to match nested array

Tags:

mongodb

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.

like image 474
Basten Gao Avatar asked Mar 23 '16 01:03

Basten Gao


People also ask

How do I match an array in MongoDB?

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria. If you specify only a single <query> condition in the $elemMatch expression, and are not using the $not or $ne operators inside of $elemMatch , $elemMatch can be omitted.

How do I find an element in an array in MongoDB?

To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }

Can we use $in in elemMatch?

This will match any document which has an array element with both 313 and either 6 or 19. It also works with {$in:[]} for both defindex and _particleEffect, as long as you intend to match any combination of the two lists. Save this answer.

How do I query an array of objects in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.


2 Answers

$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} 
like image 183
Rahul Avatar answered Oct 30 '22 10:10

Rahul


try this,it help me a lot.

{ 
  "array1": {
    "$elemMatch": {
      "array2": {
        "$elemMatch": {
          "c": 3
        }
      }
    }
  }
}
like image 43
hi54yt Avatar answered Oct 30 '22 12:10

hi54yt