Only insert if a value is unique in MongoDB else update

To only insert if a value is unique in MongoDB (or update if it exists), use the upsert option with the update() method. When upsert: true is specified, MongoDB performs an update if the document matches the query criteria, or inserts a new document if no match is found.

Syntax

db.collection.update(
    { field: "matchValue" },
    { $set: { field: "newValue" } },
    { upsert: true }
);

Sample Data

db.onlyInsertIfValueIsUniqueDemo.insertMany([
    {"StudentName": "Larry", "StudentAge": 22},
    {"StudentName": "Mike", "StudentAge": 21},
    {"StudentName": "Sam", "StudentAge": 24}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c9a633815e86fd1496b38a4"),
        ObjectId("5c9a634a15e86fd1496b38a5"), 
        ObjectId("5c9a635015e86fd1496b38a6")
    ]
}
db.onlyInsertIfValueIsUniqueDemo.find();
{
    "_id": ObjectId("5c9a633815e86fd1496b38a4"),
    "StudentName": "Larry",
    "StudentAge": 22
}
{
    "_id": ObjectId("5c9a634a15e86fd1496b38a5"),
    "StudentName": "Mike",
    "StudentAge": 21
}
{
    "_id": ObjectId("5c9a635015e86fd1496b38a6"),
    "StudentName": "Sam",
    "StudentAge": 24
}

Case 1: Update Existing Value

When the value already exists, it gets updated ?

db.onlyInsertIfValueIsUniqueDemo.update(
    {StudentName: "Mike"},
    {$set: {"StudentAge": 27}},
    { upsert: true}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Mike's age was updated from 21 to 27 since the document already existed.

Case 2: Insert New Unique Value

When the value is unique and doesn't exist, it gets inserted ?

db.onlyInsertIfValueIsUniqueDemo.update(
    {StudentName: "David"},
    {$set: {"StudentAge": 25}},
    { upsert: true}
);
WriteResult({
    "nMatched": 0,
    "nUpserted": 1,
    "nModified": 0,
    "_id": ObjectId("5c9a654ce628c11759caea54")
})

Verify Results

db.onlyInsertIfValueIsUniqueDemo.find();
{
    "_id": ObjectId("5c9a633815e86fd1496b38a4"),
    "StudentName": "Larry",
    "StudentAge": 22
}
{
    "_id": ObjectId("5c9a634a15e86fd1496b38a5"),
    "StudentName": "Mike",
    "StudentAge": 27
}
{
    "_id": ObjectId("5c9a635015e86fd1496b38a6"),
    "StudentName": "Sam",
    "StudentAge": 24
}
{
    "_id": ObjectId("5c9a654ce628c11759caea54"),
    "StudentName": "David",
    "StudentAge": 25
}

Conclusion

The upsert: true option provides conditional insert/update behavior: it updates existing documents that match the query or inserts new ones when no match is found. This ensures data uniqueness while allowing updates to existing records.

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

816 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements