Upsert in MongoDB while using custom _id values to insert a document if it does not exist?

To perform an upsert with custom _id values in MongoDB, use update() with the upsert option instead of insert(). When you use insert() with existing _id values, MongoDB throws a duplicate key error. The upsert operation inserts a document if it doesn't exist or updates it if it does.

Syntax

db.collection.update(
    { "_id": customIdValue },
    { $set: { field1: "value1", field2: "value2" } },
    { upsert: true }
);

Sample Data

First, let's create a collection and demonstrate the duplicate key error with insert() ?

db.customIdDemo.insert({"_id":1,"StudentName":"John"});
WriteResult({ "nInserted" : 1 })

Trying to insert the same _id again causes an error ?

db.customIdDemo.insert({"_id":1,"StudentName":"Carol"});
WriteResult({
    "nInserted" : 0,
    "writeError" : {
        "code" : 11000,
        "errmsg" : "E11000 duplicate key error collection: admin.customIdDemo index: _id_ dup key: { : 1.0 }"
    }
})

Solution: Using Upsert

Use update() with upsert option to insert if the document doesn't exist ?

db.customIdDemo.update(
    {"_id": 1}, 
    {$set: {"StudentName": "Carol"}}, 
    {upsert: true}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

For a non-existing document ?

db.customIdDemo.update(
    {"_id": 4}, 
    {$set: {"StudentName": "David"}}, 
    {upsert: true}
);
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 4 })

Verify Results

db.customIdDemo.find().pretty();
{ "_id" : 1, "StudentName" : "Carol" }
{ "_id" : 4, "StudentName" : "David" }

Conclusion

Use update() with upsert: true to safely insert documents with custom _id values. This avoids duplicate key errors and either inserts new documents or updates existing ones based on the _id match.

Updated on: 2026-03-15T00:28:48+05:30

661 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements