Home > Net >  update multiple document with different values
update multiple document with different values

Time:11-30

I am using mongodb node driver.

the thing is that I have 5 users in my mongodb and they have a key name points, every user has different numbers as point. I want to to update points of four user and I don't want to call for 4 times to update points of users

db.collection('users').update({id:1},{$inc : {points:5}})

(id and points will be different for every user)

is there a way to do in one call?

thanks

CodePudding user response:

This should work:

db.collection('users').updateMany({id: { $in: [id1, id2, ...] }},{$inc : {points:5}})

It matches the documents with the specified id's, and increments the documents according to the update document. I'm currently in no place to test this, but I'm positive it (or something similar) will work

CodePudding user response:

You can use a bulkWrite to send several at once:

db.collection("users").bulkWrite([
 {updateOne:{filter:{id:1},update:{$inc : {points:5}}}},
 {updateOne:{filter:{id:2},update:{$inc : {points:4}}}},
 {updateOne:{filter:{id:3},update:{$inc : {points:3}}}},
 {updateOne:{filter:{id:4},update:{$inc : {points:2}}}}
])
  • Related