Find and replace NumberLong type field in MongoDB?

To find and replace NumberLong type fields in MongoDB, use the $set operator with update() or updateMany(). This allows you to match documents containing specific NumberLong values and replace them with new NumberLong values.

Syntax

db.collection.update(
    { "fieldName": NumberLong(oldValue) },
    { $set: { "fieldName": NumberLong(newValue) } },
    { multi: true }
);

Sample Data

db.findAndReplaceDemo.insertMany([
    { "UserId": NumberLong(101) },
    { "UserId": NumberLong(110) },
    { "UserId": NumberLong(101) },
    { "UserId": NumberLong(120) },
    { "UserId": NumberLong(130) }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cd2c960b64f4b851c3a13b6"),
        ObjectId("5cd2c966b64f4b851c3a13b7"),
        ObjectId("5cd2c969b64f4b851c3a13b8"),
        ObjectId("5cd2c96cb64f4b851c3a13b9"),
        ObjectId("5cd2c96eb64f4b851c3a13ba")
    ]
}

Display Current Data

db.findAndReplaceDemo.find();
{ "_id": ObjectId("5cd2c960b64f4b851c3a13b6"), "UserId": NumberLong(101) }
{ "_id": ObjectId("5cd2c966b64f4b851c3a13b7"), "UserId": NumberLong(110) }
{ "_id": ObjectId("5cd2c969b64f4b851c3a13b8"), "UserId": NumberLong(101) }
{ "_id": ObjectId("5cd2c96cb64f4b851c3a13b9"), "UserId": NumberLong(120) }
{ "_id": ObjectId("5cd2c96eb64f4b851c3a13ba"), "UserId": NumberLong(130) }

Example: Replace NumberLong Value

Replace all occurrences of NumberLong(101) with NumberLong(10001) ?

db.findAndReplaceDemo.update(
    { "UserId": NumberLong(101) },
    { $set: { "UserId": NumberLong(10001) } },
    { multi: true }
);
WriteResult({ "nMatched": 2, "nUpserted": 0, "nModified": 2 })

Verify the Result

db.findAndReplaceDemo.find();
{ "_id": ObjectId("5cd2c960b64f4b851c3a13b6"), "UserId": NumberLong(10001) }
{ "_id": ObjectId("5cd2c966b64f4b851c3a13b7"), "UserId": NumberLong(110) }
{ "_id": ObjectId("5cd2c969b64f4b851c3a13b8"), "UserId": NumberLong(10001) }
{ "_id": ObjectId("5cd2c96cb64f4b851c3a13b9"), "UserId": NumberLong(120) }
{ "_id": ObjectId("5cd2c96eb64f4b851c3a13ba"), "UserId": NumberLong(130) }

Key Points

  • Use multi: true to update all matching documents, not just the first one.
  • The NumberLong() constructor ensures the value remains a 64-bit integer type.
  • Both the query condition and replacement value must use NumberLong() for type consistency.

Conclusion

Use update() with $set to find and replace NumberLong values in MongoDB. The multi: true option ensures all matching documents are updated, maintaining proper NumberLong data types throughout the operation.

Updated on: 2026-03-15T01:03:45+05:30

541 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements