Home > Blockchain >  how to add values using mongodb aggregation
how to add values using mongodb aggregation

Time:12-06

is there any way to add values via aggregation like db.insert_one

x = db.aggregate([{
    "$addFields": {
        "chat_id": -10013345566,
    }
}])

i tried this but this code return nothing and values are not updated

i wanna add the values via aggregation cuz aggregation is way faster than others

sample document :

    {"_id": 123 , "chat_id" : 125}
    {"_id": 234, "chat_id" : 1325}
    {"_id": 1323 , "chat_id" : 335}

expected output :

alternative to db.insert_one() in mongodb aggregation

CodePudding user response:

You have to make use of $merge stage to save output of the aggregation to the collection.

Note: Be very very careful when you use $merge stage as you can accidentally replace the entire document in your collection. Go through the complete documentation of this stage before using it.

db.collection.aggregate([
  {
    "$match": {
      "_id": 123
    }
  },
  {
    "$addFields": {
      "chat_id": -10013345566,
      
    }
  },
  {
    "$merge": {
      "into": "collection",  // <- Collection Name
      "on": "_id",  // <- Merge operation match key
      "whenMatched": "merge"  // <- Operation to perform when matched
    }
  },
])

Mongo Playground Sample Execution

  • Related