Home > Net >  How can I add a field to a MongoDB collection based off a field in the same collection?
How can I add a field to a MongoDB collection based off a field in the same collection?

Time:06-30

How can I add a field to a MongoDB collection based on a field in the same collection? For example, in this Collection:

{"_id" : "Apple", "colour": "green"}
{"_id" : "Apple", "colour": "red"}

I would like to add a third field in the collection "isGreen" so it would look like this:

{"_id" : "Apple", "colour" : "green", "isGreen" : "yes"}
{"_id" : "Apple", "colour" : "red", "isGreen" : "no"}

Is this possible with an aggregation?

CodePudding user response:

Use $set stage with $cond operator.

db.collection.aggregate([
  {
    $set: {
      "isGreen": {
        $cond: {
          if: {
            $eq: [
              "$colour",
              "green"
            ]
          },
          then: "yes",
          else: "no"
        }
      }
    }
  }
])

Sample Mongo Playground

  • Related