3 / 3
Jun 2024

A question about updateMany():
According to the documentation, the response includes

  • matchedCount containing the number of matched documents
  • modifiedCount containing the number of modified documents

Is it possible that the two numbers are different, i.e. that it was not possible to update a document for some reason?
And how do I find out which one it is?
I can’t find anything about this in the documentation …

Yes. If modifiedCount is smaller than matchedCount, it means that some matched documents were not modified because they already contained the correct updated value. For example,

{ _id : 0 , a : 0 , b : 2 }
{ _id : 1 , a : 0 , b : 3 }
updateMany( { a : 0 } , { $set : { b : 2 } } )

Both documents _id:0 and _id:1 match the query a:0 so matchedCount=2 but since _id:0 already has b:2 it is not modified. Then modifiedCount=1.

I have not seen a condition where modifiedCount is > matchedCount.

I do not know.

Hi @steevej,
thanks for your response.

That’s fine since that means when the updateMany() is finished all matched documents match the expected state regarding the update.
In this case the difference between matchedCount and modifiedCount is fine.

And how do I find out which one it is?

In fact that is only relevant for me if this would mean that one or more documents could not be updated for some other reason than you mentioned. Meaning that updating a document failed and it does not match the expected update state.