【问题标题】:how to get data from mongodb collection by match data in subdocument?如何通过子文档中的匹配数据从 mongodb 集合中获取数据?
【发布时间】:2014-11-19 18:21:11
【问题描述】:

我有像

这样的数据的 mongodb 集合
   var data = [
{
    name: 'test1',
    attributes: [
        {
            name: 'color',
            value: 'red'
        },
        {
            name: 'size',
            value: 'L'
        }
    ]
},
{
    name: 'test2',
    attributes: [
        {
            name: 'color',
            value: 'blue'
        },
        {
            name: 'size',
            value: 'S'
        }
    ]
},
{
    name: 'test3',
    attributes: [
        {
            name: 'color',
            value: 'red'
        },
        {
            name: 'size',
            value: 'S'
        }
    ]
}

]

如何查询数据库,以便返回匹配属性名称“color”的值为“red”和属性名称“size”的值为“L”的文档?

意味着它应该返回

 var output = [
{
    name: 'test1',
    attributes: [
        {
            name: 'color',
            value: 'red'
        },
        {
            name: 'size',
            value: 'L'
        }
    ]
}

]

【问题讨论】:

  • 请问您为什么没有{name:'test1',color:'red',size:'L'}?只是好奇。

标签: mongodb


【解决方案1】:

您可以在find 查询中使用$and 运算符。

db.collection.find({$and:[{"attributes.name":"color","attributes.value":"red"}, 
                          {"attributes.name":"size","attributes.value":"L"}]})

【讨论】:

  • 此处指定的条件需要匹配数组中的 2 个文档,$and 有帮助吗?
  • 是的。 $and 查找符合其所有条件的文档。属性数组中的第一个元素满足第一个条件,第二个元素满足第二个条件。即使数组中有另一个属性子文档不符合这两个条件,该文档也会被返回。
猜你喜欢
  • 2018-10-08
  • 1970-01-01
  • 2020-09-05
  • 2021-07-20
  • 1970-01-01
  • 1970-01-01
  • 2018-07-14
  • 2016-01-22
  • 2020-08-15
相关资源
最近更新 更多