Updating document/s

is there a rule of thumb on how many documents gets updated with witch operation?

for example, some operations update one document but other update many documents.

I don’t mean the db..updateOne/updatemany/update()

but in side of these commands like $set,and $addFeileds … etc.

is there a way to know that?

Hello @Abdullah_Alfadhel,

If you notice any of the three update methods updateOne(), updateMany() and update(), there are many parameters you can specify. For example,

db.collection.updateOne(
   <filter>,
   <update>,
   { <other options> }
)

The filter specifies the documents to match for an update. The update specifies the modifications (or changes) to be made in the matching document(s).

There are two ways you can specify the modifications in the update operation. This is by specifying the:

  1. Update with an Update Operator Expressions Document - here you use update operators like $set. $inc, $push, …
  2. Update with Aggregation Pipeline - here you use aggregation stages like $set, $unset, …

And, the update do not determine how many documents get updated - just how each document gets updated. The number of documents that get updated is determined by the filter.

There is a result document returned after the updated is completed, and it shows how many documents are modified: [ See details at Update Returns ].


The Update Methods:

Each of these three methods have specific behavior and purpose.

The updateOne method can update at most one document only. The name of the method says so. The method takes filter as an argument. The update happens only when the filter has a match. If more than one document match, the first document will be updated.

The updateMany also has a filter to match and can update more than one document.

The update can be used for updating a single document or multiple documents.The method has an optional parameter multi: true, which specifies that multiple documents can be updated.

Note that all the three methods have the filter to match the documents to be updated. If no documents match the condition specified in the filter, there will be no modified document(s).

1 Like

but if the filter matched more than one document, what will happen? in the case of updateOne() and update() ?

By default, in both cases the first matching document will be modified. In case, of update and if you specify the multi: true option, then all the matched documents will be modified.

1 Like