1

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.

Kesem David
  • 2,135
  • 3
  • 27
  • 46
  • 1
    You can have a situation when you don't have anything to upsert so `upsertedCount = 0` and the update you did to existing document modified the value of the field to same value as before which will have `modifiedCount = 0`. So in this situation you'll have `matchedCount != 0` – s7vr Jan 18 '17 at 16:38
  • @Veeram Saying "you dont have anything to upsert" you mean the document already exists? Plus you claim that `update` of mongo actually updates only relevant values? I figured mongo just overrides the document with the new one.. And say you're right, if it only updates the relevant values, it won't be updating a field of the same value, am I right? – Kesem David Jan 19 '17 at 07:21
  • *"you dont have anything to upsert" you mean the document already exists?* Yes. *Plus you claim that update of mongo actually updates only relevant values? I figured mongo just overrides the document with the new one.* Mongo has both selective update and replacement. *And say you're right, if it only updates the relevant values, it won't be updating a field of the same value, am I right?* Yes and the modified count will be 0. – s7vr Jan 19 '17 at 13:57

2 Answers2

2

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)

masterforker
  • 2,443
  • 2
  • 25
  • 39
0

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.

Boris Mulder
  • 308
  • 2
  • 14