【问题标题】:MongoDB: How to find with whole arrayMongoDB:如何查找整个数组
【发布时间】:2019-12-17 21:17:39
【问题描述】:

我是 MongoDB 新手。

我想查找与整个数组匹配的文档。

让我们向您展示集合架构。 这里是组合收集数据

{
   _id: 741258,
   product_id: 258,
   attributes: [ { attr_id: 123, val: '26' },
                 { attr_id: 456, val: 'Blue' },
                 { attr_id: 789, val: 'Slim' } ],
},
{
   _id: 745896,
   product_id: 258,
   attributes: [ { attr_id: 124, val: '28' },
                 { attr_id: 484, val: 'Red' },
                 { attr_id: 852, val: 'Small' } ],
},
{
   _id: 985632,
   product_id: 258,
   attributes: [ { attr_id: 123, val: '26' },
                 { attr_id: 456, val: 'Blue' } ],
},
{
   _id: 456855,
   product_id: 258,
   attributes: [ { attr_id: 123, val: '26' } ],
}

查询:


db.combination.find( { product_id: "258" },
                 { attributes: { $elemMatch: [ { attr_id: 123, val: '26' },
                                               { attr_id: 456, val: 'Blue' } 
                                             ] } } )

错误:


(node:4460) UnhandledPromiseRejectionWarning: MongoError: $elemMatch needs an Object

预期结果:


{
   _id: 985632,
   product_id: 258,
   attributes: [ { attr_id: 123, val: '26' },
                 { attr_id: 456, val: 'Blue' } ],
},

请帮助减缓这个问题。提前致谢

【问题讨论】:

    标签: node.js mongodb find


    【解决方案1】:

    您不需要使用$elemMatch,解决方案要简单得多。

    对于数组的精确匹配,您只需要指定要匹配的孔数组。

    例如,要达到预期的结果,你只需要查询:

    db.collection.find({
      attributes: [
        {
          attr_id: 123,
          val: "26"
        },
        {
          attr_id: 456,
          val: "Blue"
        }
      ]
    })
    

    请注意,它需要完全相同,如果您交换任何对象内的属性顺序,您的查询将与所需的文档不匹配。

    例如,以下查询将不会返回所需的文档:

    db.collection.find({
      attributes: [
        {
          attr_id: 123,
          val: "26"
        },
        {
          val: "Blue", // swaped attributes order
          attr_id: 456
        }
      ]
    })
    

    有关如何查询嵌套数组的更多信息,请访问this documentation page

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-06
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      • 2022-01-22
      • 2018-07-23
      • 2011-12-30
      相关资源
      最近更新 更多