Update with conditions

I have next document
user = {
_id: ObjectID
name: string // it is unique
modified: Time,
field1:
field2:

fieldN
}
And I want to add new_user to collection with next logic.

  1. If user with name equal new_user.name does not exists, then add new_user
  2. If user with such name exists, but user.modified<new_user.modified, then update user.field1,…,user.fieldN, and user.modified
  3. If user with such name exists, but user.modified>new_user.modified then do nothing.

It is possible to do this using findOne and then insertOne or updateOne commands. But can be such logic done with single command?

And additional question. I have a bunch of users and I want to do this logic for these users. Can I perform it with single command, like updateMany with some params?

It is possible to do this using findOne and then insertOne or updateOne commands. But can be such logic done with single command?

The db.collection.update method has features that address the questions you have about insert when not exists, update and conditional update. Please refer these documentation links (all are on one page and related):


And additional question. I have a bunch of users and I want to do this logic for these users. Can I perform it with single command, like updateMany with some params?

The updateMany can be used to update multiple documents. If you are able to apply your logic with one user data, I think, it can be applied to multiple documents at a time using this method.