Insert records in MongoDB collection if it does not exist?

You can use the update() function with the upsert option to insert records in MongoDB if they do not exist. When upsert is set to true, MongoDB will create a new document if no matching document is found.

Syntax

db.collection.update(
    { "field": "value" },
    { "field": "value", "field2": "value2" },
    { upsert: true }
);

Create Sample Data

db.insertIfNotExistsDemo.insertMany([
    { "StudentName": "Mike", "StudentAge": 21 },
    { "StudentName": "Sam", "StudentAge": 22 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c7eec7b559dd2396bcfbfc2"),
        ObjectId("5c7eec97559dd2396bcfbfc3")
    ]
}

Verify Existing Documents

db.insertIfNotExistsDemo.find().pretty();
{
    "_id": ObjectId("5c7eec7b559dd2396bcfbfc2"),
    "StudentName": "Mike",
    "StudentAge": 21
}
{
    "_id": ObjectId("5c7eec97559dd2396bcfbfc3"),
    "StudentName": "Sam",
    "StudentAge": 22
}

Insert Record If It Does Not Exist

Use the update() method with upsert option to insert David's record if it doesn't exist ?

key = { "StudentName": "David" };
value = { "StudentName": "David", "StudentAge": 26 };
db.insertIfNotExistsDemo.update(key, value, { upsert: true });
WriteResult({
    "nMatched": 0,
    "nUpserted": 1,
    "nModified": 0,
    "_id": ObjectId("5c7eecd4c743760e97af8261")
})

Verify Result

db.insertIfNotExistsDemo.find().pretty();
{
    "_id": ObjectId("5c7eec7b559dd2396bcfbfc2"),
    "StudentName": "Mike",
    "StudentAge": 21
}
{
    "_id": ObjectId("5c7eec97559dd2396bcfbfc3"),
    "StudentName": "Sam",
    "StudentAge": 22
}
{
    "_id": ObjectId("5c7eecd4c743760e97af8261"),
    "StudentName": "David",
    "StudentAge": 26
}

Key Points

  • nMatched: 0 indicates no existing document was found matching the criteria
  • nUpserted: 1 confirms a new document was inserted
  • The upsert option prevents duplicate insertions when the document already exists

Conclusion

The update() method with upsert: true effectively handles conditional inserts in MongoDB. It inserts new documents only when no matching document exists, preventing duplicates while ensuring data consistency.

Updated on: 2026-03-15T00:04:08+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements