英文:
MongoDB , $project a field depending on the existance of another field
问题
如标题所示,我想要仅在“x”字段不存在时投影“y”字段。
英文:
As the title says, i want to project for example the "y" field only if "x" field does not exsist.
[
  {
    "_id": "1",
    "y": "project"
  },
  {
    "_id": "2",
    "x": "has x",
    "y": "don't project"
  }
]
Thanks in advance.
答案1
得分: 0
如果我理解正确,您可以在$project阶段中使用$cond来决定是否投影字段:
在这里,如果x存在,那么将移除(不投影)字段y,否则将显示y的值。
db.collection.aggregate([
  {
    "$project": {
      "_id": 1,
      "y": {
        "$cond": {
          "if": {"$gt": ["$x", null]},
          "then": "$$REMOVE",
          "else": "$y"
        }
      }
    }
  }
])
示例在这里
注意,您也可以投影字段x。查看此示例。
英文:
If I've understood correctly you can use $cond into a $project stage to decide if project or not a field:
Here if x exists then remove (does not project) the field y, otherwise the y value is shown.
db.collection.aggregate([
  {
    "$project": {
      "_id": 1,
      "y": {
        "$cond": {
          "if": {"$gt": ["$x",null]},
          "then": "$$REMOVE",
          "else": "$y"
        }
      }
    }
  }
])
Example here
Note that also you can project the field x. Check this example
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论