Search code examples
mongodbmongoose

MongoDB , $project a field depending on the existance of another field


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.


Solution

  • 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