使用文档数组而不是字符串数组的MongoDB $ redact

时间:2014-10-10 17:35:35

标签: mongodb mongodb-query

以下是我设计的“着名食谱”数据库的概念结构。

此结构与$ redact聚合章节中的MongoDB示例类似。

最大的区别在于我希望对部分和子部分进行命名访问,以及存储在“tags”数组中的对象中的其他信息,而不是MongodB示例中的简单字符串。

问题是我无法制作$ redact条件,因此它可以正确检查tags.name属性。我在条件中使用$ elemMatch是不成功的,点符号也会引发错误。

有什么建议吗?

{
   _id: 1,
   title: "Secret Recipes of Fast Food Chains",
   tags: [
     { name: "Colonel Sanders", access: ["read"] },
     { name: "Ronald  McDonald", access: ["read"] }
   ],
   year: 2014,
   subsections: [
       {
       subtitle: "Colonel Sander's Famous Recipe",
       tags: [
         { name: "Colonel Sanders", access: ["update", "delete"] },
         { name: "Ronald McDonald"}
       ],
       ingredients: ["salt", "pepper", "paprika", "garlic powder"]
       ]
   {
       subtitle: "Ronald McDonald's McNugget Sauce",
       tags: [
         { name: "Colonel Sanders" },
         { name: "Ronald McDonald", access: ["update", "delete"]  } 
       ],
       ingredients: ["mustard", "ketchup", "salt", "vinegar"]
   }
}

我的非工作查询会读到这样的内容:

var access = "Colonel Sanders"
db.recipes.aggregate(
  [
    { $match: { "year": 2014 } },
    { $redact:
    {
        $cond: {
                 if: { $eq: [ tags: { $elemMatch : { "name" } }, access ] },
                 then: "$$DESCEND",
                 else: "$$PRUNE"
               }
      }
    }
  ]
)

1 个答案:

答案 0 :(得分:0)

老问题,但我遇到了同样的问题。

首先,您的示例已修复:

db.recipes.insert({
  _id: 1,
  title: "Secret Recipes of Fast Food Chains",
  tags: [{
    name: "Colonel Sanders",
    access: ["read"]
  }, {
    name: "Ronald  McDonald",
    access: ["read"]
  }],
  year: 2014,
  subsections: [{
    subtitle: "Colonel Sander's Famous Recipe",
    tags: [{
      name: "Colonel Sanders",
      access: ["update", "delete"]
    }, {
      name: "Ronald McDonald"
    }],
    ingredients: ["salt", "pepper", "paprika", "garlic powder"]
  }, {
    subtitle: "Ronald McDonald's McNugget Sauce",
    tags: [{
      name: "Colonel Sanders"
    }, {
      name: "Ronald McDonald",
      access: ["update", "delete"]
    }],
    ingredients: ["mustard", "ketchup", "salt", "vinegar"]
  }]
})

之后我编写了以下查询:

var access = "Colonel Sanders"
db.recipes.aggregate(
  [{
    $match: {
      "year": 2014
    }
  }, {
    $redact: {
      $cond: {
        if : {
          $or: [{$eq: ["$name", access]}, {$not: "$name"}]
        },
        then: "$$DESCEND",
        else :"$$PRUNE"
      }
    }
  }]
)

试一试。您可以在其他问题上找到更多信息:3985214