MongoDB查询生成OR响应而不是AND

jwe*_*rre 6 mongodb

我正在使用MongoDB版本2.6.5,我有一个看起来像这样的集合:

{
  "_id": ObjectId("555a3398f4c572a44f877dcd"),
  "created": ISODate("2015-05-18T17:02:14.951Z"),
  "values": [
    {
      "value": "4",
      "label": "Apple"
    },
    {
      "value": "5",
      "label": "Peach"
    },
    {
      "value": "5",
      "label": "Banana"
    },
    {
      "value": "4",
      "label": "Orange"
    }
  ],
  "__v": 0
}
{
  "_id": ObjectId("555a74dbdfe135105faccdf7"),
  "created": ISODate("2015-05-18T21:27:37.064Z"),
  "values": [
    {
      "value": "2",
      "label": "Apple"
    },
    {
      "value": "3",
      "label": "Peach"
    },
    {
      "value": "4",
      "label": "Banana"
    },
    {
      "value": "5",
      "label": "Orange"
    }
  ],
  "__v": 0
}
{
  "_id": ObjectId("555a74f9dfe135105faccdfa"),
  "created": ISODate("2015-05-18T21:27:37.064Z"),
  "values": [
    {
      "value": "1",
      "label": "Apple"
    },
    {
      "value": "1",
      "label": "Peach"
    },
    {
      "value": "1",
      "label": "Banana"
    },
    {
      "value": "1",
      "label": "Orange"
    }
  ],
  "__v": 0
}
Run Code Online (Sandbox Code Playgroud)

当我试图获得具有values.label"橙色"和values.value"5"的文档时,我应该得到一份文件,但我得到两份:

> db.answers.count({ 'values.label':'Orange', 'values.value':'5' })
> 2
Run Code Online (Sandbox Code Playgroud)

这是使用id选择两个文档:( 555a3398f4c572a44f877dcd可能因为Banana它的值也是5)和555a74dbdfe135105faccdf7(这是唯一正确的文档 ).谁能想到为什么会这样?

mne*_*syn 7

您正在使用数组上的点符号(用于到达对象).虽然它以你描述的方式工作,但它确实暗示了OR逻辑,因为整个数组被解释为一个对象,可以这么说.

您希望在数组中的文档上匹配多个条件,这是$elemMatch运算符的用途,即

db.answers.count({ 'values' : { '$elemMatch' : { 'label':'Orange', 'value':'5' } } })
Run Code Online (Sandbox Code Playgroud)