1

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

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

我怎样才能找到所有的食谱:

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

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

总结:我需要所有包含牛奶、巧克力或两者兼有的食谱,但别无其他。

4

1 回答 1

2

使用正则表达式查找包含ingredients牛奶或巧克力的文档(使用此处的技术),然后用 a 否定它就可以了$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"
    }
  ]
}
于 2013-02-08T13:33:05.123 回答