Notification texts go here Contact Us Buy Now!

Can modifiedCount and upsertedCount both be 0?

There are a few scenarios where both modifiedCount and upsertedCount can be 0:

  • When a filter within the update operation does not match:
  • db.collection.updateOne(
        {_id: 2},
        { $set: { items.$[elem]: 4 } },
        { arrayFilters: [{elem: 3}], upsert: true }
    )
    
    In this example, the filter {elem: 3} will not match any element in the items array. As a result, the document will be found (setting matchedCount to 1), but no modifications will be made (setting both modifiedCount and upsertedCount to 0).
  • When using $setOnInsert:
  • db.collection.updateOne(
      { name: "David" },
      { $setOnInsert: { firstSeenAt: new Date() } },
      { upsert: true }
    )
    
    In this example, if the document with name: "David" already exists, the update operation will not modify the document (setting modifiedCount to 0). However, since upsert is set to true, the firstSeenAt field will be set if the document does not exist, resulting in upsertedCount being 0 as well.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.