How to use elemMatch to match nested array

前端 未结 2 1983
忘了有多久
忘了有多久 2021-01-02 09:37

I have some data structure like this

{
  a: 1,
  array1: [
    {
      b: 2
      array2: [
        { 
          // this is my target
          c: 3,
                


        
相关标签:
2条回答
  • 2021-01-02 09:43

    try this,it help me a lot.

    { 
      "array1": {
        "$elemMatch": {
          "array2": {
            "$elemMatch": {
              "c": 3
            }
          }
        }
      }
    }
    
    0 讨论(0)
  • 2021-01-02 09:59

    $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} 
    
    0 讨论(0)
提交回复
热议问题