如何使用elemMatch匹配嵌套数组 [英] How to use elemMatch to match nested array

查看:148
本文介绍了如何使用elemMatch匹配嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些这样的数据结构

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
        }          
      ]
    }
  ]
}

我知道使用{"array1" : {"$elemMatch" : {"b" : 2} } }来匹配第一级array1的元素.但是我不知道如何匹配array1的array2的元素{c: 3, d: 3}.

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.

推荐答案

$elemMatch用于声明同一嵌套结构内多个字段之间的关联.

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

例如如果要查询c和d并需要它们属于同一子文档,则可以像这样查询它.

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} } } 

注意:如果要查询单个字段,则实际上不需要使用$elemMatch(因为没有关联)

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} 

这篇关于如何使用elemMatch匹配嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆