MongoDB query to convert string to int?

To convert string to int in MongoDB, you can use parseInt() with forEach() for iteration or the $toInt operator for aggregation pipelines. The forEach() method allows you to iterate through documents and modify field types.

Syntax

// Method 1: Using forEach() with parseInt()
db.collection.find().forEach(function(doc) {
    doc.fieldName = parseInt(doc.fieldName);
    db.collection.save(doc);
});

// Method 2: Using $toInt in aggregation
db.collection.aggregate([
    { $addFields: { fieldName: { $toInt: "$fieldName" } } }
]);

Sample Data

db.demo369.insertMany([
    { "Price": "1000000" },
    { "Price": "1747864" },
    { "Price": "19548575" }
]);
{
    "acknowledged": true,
    "insertedIds": {
        "0": ObjectId("5e57e2e32ae06a1609a00aed"),
        "1": ObjectId("5e57e2e92ae06a1609a00aee"),
        "2": ObjectId("5e57e2ee2ae06a1609a00aef")
    }
}

Display Current Data

db.demo369.find();
{ "_id": ObjectId("5e57e2e32ae06a1609a00aed"), "Price": "1000000" }
{ "_id": ObjectId("5e57e2e92ae06a1609a00aee"), "Price": "1747864" }
{ "_id": ObjectId("5e57e2ee2ae06a1609a00aef"), "Price": "19548575" }

Method 1: Using forEach() with parseInt()

db.demo369.find().forEach(function(d) {
    d.Price = parseInt(d.Price);
    db.demo369.save(d);
});

Verify Result

db.demo369.find();
{ "_id": ObjectId("5e57e2e32ae06a1609a00aed"), "Price": 1000000 }
{ "_id": ObjectId("5e57e2e92ae06a1609a00aee"), "Price": 1747864 }
{ "_id": ObjectId("5e57e2ee2ae06a1609a00aef"), "Price": 19548575 }

Method 2: Using $toInt (Modern Approach)

db.demo369.updateMany(
    {},
    [{ $set: { Price: { $toInt: "$Price" } } }]
);

Key Points

  • parseInt() with forEach() modifies documents directly and permanently updates the collection.
  • $toInt operator is the modern approach for type conversion in aggregation pipelines.
  • Use updateMany() with aggregation pipeline for bulk field type conversions.

Conclusion

Both parseInt() with forEach() and $toInt operator effectively convert string fields to integers. The $toInt approach is preferred for modern MongoDB versions as it's more efficient for bulk operations.

Updated on: 2026-03-15T02:41:43+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements