How Do I copy a column into another column and create column if it is not present in Mongo DB

Viewed 306

I have 2 columns A and B, Data I have is daily from Feb to July.For Feb to march I dont have Column B. My Task is as follows

Task 1 : if Column B is not present create a column in document and copy A Column to B

Task 2: If column already exists leave it with data.

Tried so far: col.find({colb:{"$exisits:True", "$set"}})....

please guide me

1 Answers

You need to use MongoDB aggregation. The $ifNull operator is what you need.

db.collection.aggregate([
  {
    "$addFields": {
      "colb": {
        "$ifNull": [
          "$colb",
          "$cola"
        ]
      }
    }
  }
])

MongoPlayground

With $project

db.collection.aggregate([
  {
    "$project": {
      "cola": "$cola",
      "colb": {
        "$ifNull": [
          "$colb",
          "$cola"
        ]
      }
    }
  }
])

MongoPlayground

Related