manoj
manoj

Reputation: 5643

Update Collection by using Data from that Collection in mongodb

I Have a collection which has data like {m:1,n:3}

want to update this collection like {m:1,n:3,s:4}

where s= m+n in mongodb,

so for that, I tried

db.data.update({},{$set:{s:(m+n)}); 

but it doesn't work and I tried multiple things but still haven't a solution. How can I achieve this?

Upvotes: 1

Views: 29

Answers (1)

Saravana
Saravana

Reputation: 12817

with aggregation you can $addFields and $out to a collection

db.col.aggregate([
    {$addFields : {s : {$add:["$m", "$n"]}}},
    {$out : "col"}
])

with $project for mongo version less than 3.4

db.col.aggregate([
    {$project : {m:1, n:1, s : {$add:["$m", "$n"]}}},
    {$out : "col"}
])

result

> db.col.drop()
true

> db.col.insert({m:2,n:4})
WriteResult({ "nInserted" : 1 })

> db.col.find()
{ "_id" : ObjectId("5a911efc6bb20635697c6b17"), "m" : 2, "n" : 4 }

> db.col.aggregate([{$addFields : {s : {$add:["$m", "$n"]}}},{$out : "col"}])

> db.col.find()
{ "_id" : ObjectId("5a911efc6bb20635697c6b17"), "m" : 2, "n" : 4, "s" : 6 }
> 

Upvotes: 1

Related Questions