【问题标题】:How do I query nested objects within an array to match an $in array in mongodb?如何查询数组中的嵌套对象以匹配 mongodb 中的 $in 数组?
【发布时间】:2020-09-16 22:02:23
【问题描述】:

数据结构

{
    users: [
        {id: "aaa"},
        {id: "bbb"},
        {id: "ccc"}
    ]
},
{
    users: [
        {id: "111"},
        {id: "222"},
        {id: "333"}
    ]
},


array: ["111", "222", "333"]

我想获取每个“id”都与我的数组匹配的文档,就像 $in 一样。但我不希望只有三场比赛中的两场比赛。所以在这种情况下,查询应该返回第二个文档。

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    一种方式:

    查询数组中的元素

    const cursor = db.collection('inventory').find({
      users: [{id: "111"},{id: "222"},{id: "333"}]
    });
    

    https://docs.mongodb.com/manual/tutorial/query-arrays/#query-an-array-for-an-element

    相关问题: MongoDB Find Exact Array Match but order doesn't matter

    【讨论】:

      【解决方案2】:
      const userIds = ["abc", "123", ...]
      

      我发现这个查询可以解决我的问题。

          {
          $and: [
              {users: {$elemMatch: {id: {$in: userIds}}}}, 
              {users: {$size: userIds.length}}
          ]
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-01
        • 1970-01-01
        • 2018-09-10
        • 2021-08-13
        • 1970-01-01
        • 1970-01-01
        • 2020-03-28
        • 2012-07-23
        相关资源
        最近更新 更多