How to convert string to numerical values in MongoDB?

To convert string values to numerical values in MongoDB, use forEach() with parseInt() or $toInt aggregation operator. The forEach() method iterates through documents and updates each string field to its numerical equivalent.

Syntax

db.collection.find().forEach(function(doc) {
    db.collection.update(
        { "_id": doc._id },
        { "$set": { "fieldName": parseInt(doc.fieldName) } }
    );
});

Sample Data

db.convertStringToNumberDemo.insertMany([
    {"EmployeeId": "101", "EmployeeName": "Larry"},
    {"EmployeeId": "1120", "EmployeeName": "Mike"},
    {"EmployeeId": "3210", "EmployeeName": "Sam"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c7f56528d10a061296a3c31"),
        ObjectId("5c7f56648d10a061296a3c32"),
        ObjectId("5c7f566e8d10a061296a3c33")
    ]
}

View Original Data

db.convertStringToNumberDemo.find().pretty();
{
    "_id": ObjectId("5c7f56528d10a061296a3c31"),
    "EmployeeId": "101",
    "EmployeeName": "Larry"
}
{
    "_id": ObjectId("5c7f56648d10a061296a3c32"),
    "EmployeeId": "1120",
    "EmployeeName": "Mike"
}
{
    "_id": ObjectId("5c7f566e8d10a061296a3c33"),
    "EmployeeId": "3210",
    "EmployeeName": "Sam"
}

Method 1: Using forEach() with parseInt()

db.convertStringToNumberDemo.find().forEach(function(x) {
    db.convertStringToNumberDemo.update(
        { "_id": x._id },
        { "$set": { "EmployeeId": parseInt(x.EmployeeId) } }
    );
});

Verify Results

db.convertStringToNumberDemo.find().pretty();
{
    "_id": ObjectId("5c7f56528d10a061296a3c31"),
    "EmployeeId": 101,
    "EmployeeName": "Larry"
}
{
    "_id": ObjectId("5c7f56648d10a061296a3c32"),
    "EmployeeId": 1120,
    "EmployeeName": "Mike"
}
{
    "_id": ObjectId("5c7f566e8d10a061296a3c33"),
    "EmployeeId": 3210,
    "EmployeeName": "Sam"
}

Method 2: Using Aggregation with $toInt

db.convertStringToNumberDemo.aggregate([
    { $addFields: { "EmployeeId": { $toInt: "$EmployeeId" } } },
    { $out: "convertStringToNumberDemo" }
]);

Key Points

  • parseInt() converts strings to integers in JavaScript functions
  • $toInt operator converts strings to numbers in aggregation pipelines
  • Use $out stage to replace the original collection with converted values

Conclusion

Convert string to numerical values using forEach() with parseInt() for iterative updates, or use aggregation with $toInt for bulk operations. Both methods effectively transform string fields to their numerical equivalents.

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

710 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements