MongoDB,根据另一个字段的存在性进行$project字段。

huangapple go评论61阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年3月4日 05:24:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75632000.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定