1

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

2
  • Share a sample document and expected output Commented Dec 5, 2021 at 6:25
  • @hhharsha36 check edits Commented Dec 5, 2021 at 7:54

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

but i want to update only single value tho
In that case you have to make sure that only that single field and _id field are returned before the last stage and perform $merge with whenMatched: "merge" option. Regardless, what you are looking for can be achieved only by $merge stage.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.