MongoDB查询产生OR响应,而不是AND

MongoDB查询产生OR响应,而不是AND

问题描述:

我使用的是MongoDB 2.6.5版,并且有一个看起来像这样的集合:

I'm using MongoDB version 2.6.5 and I have a collection that looks something like this:

{
  "_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
}

当我尝试获取values.label为橙色"且values.value为"5"的文档时,我应该取回一个文档,但要得到两个文档:

When I try to get the document that has a values.label of "Orange" AND values.value of "5" I should get one document back but I'm getting two:

> db.answers.count({ 'values.label':'Orange', 'values.value':'5' })
> 2

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

This is selecting the two documents with ids: 555a3398f4c572a44f877dcd (presumably because Banana also has a value of 5 ) and 555a74dbdfe135105faccdf7 (which is the only correct one). Can anyone think of why this is happening?

您正在使用点标记(用于插入对象中的 ).虽然可以按照您描述的方式工作,但是它确实暗示了OR逻辑,因为可以说整个数组都被解释为对象.

You're using the dot notation (used to reach into objects) on an array. While that works in the way you described, it does imply OR-logic because the entire array is interpreted as an object, so to speak.

您要匹配数组中个文档上的多个条件,这就是

You're looking to match multiple criteria on documents in an array, which is what the $elemMatch operator is for, i.e.

db.answers.count({ 'values' : { '$elemMatch' : { 'label':'Orange', 'value':'5' } } })