子文档查询不包含具有正则表达式匹配的数组外的值

时间:2013-02-08 12:13:24

标签: mongodb

如果我有一组食谱,每个项目看起来像:

{
    name: "Recipe 1",
    ingredients: [{
        name: "dark chocolate",
        qty: "1 g"
    }, {
        name: "milk",
        qty: "2 g"
    }, {
        name: "unsalted butter",
        qty: "3 g"
    }]
}

如何找到所有食谱:

  • 的成分名称​​包含牛奶巧克力
  • 不包含含有牛奶或巧克力的任何其他成分?

上面的示例与该查询不匹配。

总结:我需要所有含有牛奶,巧克力或两者的食谱,但没有别的。

1 个答案:

答案 0 :(得分:2)

使用正则表达式查找包含ingredients牛奶或巧克力的文档而不是(使用来自here的技术)然后使用$not取消诀窍:

db.recipes.find({'ingredients.name': {$not: /^((?!(milk|chocolate)).)*$/}})

经过测试:

{
  "_id": ObjectId("5114f7b748994465c5b5c369"),
  "name": "Recipe 1",
  "ingredients": [
    {
      "name": "dark chocolate",
      "qty": "1 g"
    },
    {
      "name": "milk",
      "qty": "2 g"
    },
    {
      "name": "unsalted butter",
      "qty": "3 g"
    }
  ]
}
{
  "_id": ObjectId("5114f9f348994465c5b5c36a"),
  "name": "Recipe 2",
  "ingredients": [
    {
      "name": "dark chocolate",
      "qty": "1 g"
    },
    {
      "name": "milk",
      "qty": "2 g"
    }
  ]
}
{
  "_id": ObjectId("5114fcec48994465c5b5c36b"),
  "name": "Recipe 3",
  "ingredients": [
    {
      "name": "milk chocolate",
      "qty": "1 g"
    }
  ]
}
{
  "_id": ObjectId("5114fd0e48994465c5b5c36c"),
  "name": "Recipe 4",
  "ingredients": [
    {
      "name": "soy",
      "qty": "1 g"
    }
  ]
}
{
  "_id": ObjectId("5114fd5248994465c5b5c36d"),
  "name": "Recipe 5",
  "ingredients": [
    {
      "name": "chocolate mud",
      "qty": "1 g"
    }
  ]
}

输出:

{
  "_id": ObjectId("5114f9f348994465c5b5c36a"),
  "name": "Recipe 2",
  "ingredients": [
    {
      "name": "dark chocolate",
      "qty": "1 g"
    },
    {
      "name": "milk",
      "qty": "2 g"
    }
  ]
}
{
  "_id": ObjectId("5114fcec48994465c5b5c36b"),
  "name": "Recipe 3",
  "ingredients": [
    {
      "name": "milk chocolate",
      "qty": "1 g"
    }
  ]
}
{
  "_id": ObjectId("5114fd5248994465c5b5c36d"),
  "name": "Recipe 5",
  "ingredients": [
    {
      "name": "chocolate mud",
      "qty": "1 g"
    }
  ]
}