updateOne vs replaceOne performance

Hey community,

I’ve been developing a pattern for my application where I write get the document, edit it in memory the whole document back to the db.
This is really convenient because I don’t need to make a custom update for every bit of functionality. And this is becomes really testable in my app.

From what I can see there are two ways to update a whole collection
collection.updateOne({_id: id}, {$set: theDocument})
collection.replaceOne({_id: id}, {theDocument})

Is any method better or faster than the other?
Also I realise this might not be safe, but these documents are not operated on many times within a small time frame, for sensitive updates I write atomic updating functions.

Honestly I would insert the whole document as new, and then delete the old one.


you should not worry about being faster. That being written. If I remember correctly, existing fields with unchanged values are not modified during $set (sorry I do not remember exactly where I read that). If those unchanged fields are part of an index the replaceOne or insertThenDelete might have a much bigger impact than updateOne.

But then you can’t use the same _id, because its a unique index and now that is 2 operations. I don’t think it’s an ideal solution.

Hi @Ihsan_Mujdeci,

I’d strongly encourage not doing an entire document update or replacement.

Sending an entire document to update one or two fields (when many more fields remain the same) can quickly cause scalability problems. For example, as documents grow, sending an entire document across the network is a lot of unnecessary network traffic. Also, the oplog becomes unnecessarily bloated.

Using db.collection.updateOne with the appropriate operator (e.g. $set) is smaller and efficient when only updating fields that change.



This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.