Kesem David
Kesem David

Reputation: 2245

Can modifiedCount and upsertedCount both be 0?

I've been wondering, using update of mongodb with the {upsert:true} options, is it possible to get both upsertedCount AND modifiedCount be 0?

I understand that the upsertedCount refers to the created documents, while the modifiedCount refers to the updated documents.

So using the upsert I cannot find a scenario in which both of those will be equal to 0.

Am i wrong?

Thanks in advance for the help.

Upvotes: 1

Views: 4257

Answers (3)

Marces Engel
Marces Engel

Reputation: 784

With $setOnInsert this is actually quite realistic to happen. If that's the only operation you're using, you'll always get both being 0 if the document already existed.

db.collection.updateOne(
  { name: "David" },
  { $setOnInsert: { firstSeenAt: new Date() } },
  { upsert: true }
)

will return the following (with both upsertedCount and modifiedCount being 0)

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 0,
  upsertedCount: 0
}

Upvotes: 1

Boris Mulder
Boris Mulder

Reputation: 364

There is a case where both are zero. If you use some filter within the update operation, as opposed to within the query, and this filter does not match, it might find the document, setting matchedCount to 1, and upsertedCount to 0, but because the sub-query does not match, your modifiedCount will be 0 as well.

Example database:

{
    _id: 2
    items: [1, 2]
}

Example query:

db.collection.updateOne(
    {_id: 2},
    { $set: { items.$[elem]: 4 } },
    { arrayFilters: [{elem: 3}], upsert: true }
)

Result:

{ acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 0,
  upsertedCount: 0 }

This query is a sort of weird way to replace the 3 with a 4, but if the 4 does not exist, the document is found but not modified.

Upvotes: 0

masterforker
masterforker

Reputation: 2527

I think you are correct in your assumption. Upsert basically means create a new document if a document cannot be found. So if you set it to true while doing an update either the document is present and will be modified (setting modifiedCount to 1) or the document is not present (setting upsertCount to 1)

Upvotes: 1

Related Questions