Is it possible to cast in a MongoDB Query?

Yes, it is possible to cast in a MongoDB query using JavaScript expressions with the $where operator, which allows automatic type conversion from string to number for comparisons.

Syntax

db.collection.find("this.fieldName > value");

Sample Data

Let us create a collection with sample documents containing Amount values stored as strings ?

db.castingDemo.insertMany([
    {"Amount": "200"},
    {"Amount": "100"},
    {"Amount": "110"},
    {"Amount": "95"},
    {"Amount": "85"},
    {"Amount": "75"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c947e874cf1f7a64fa4df42"),
        ObjectId("5c947e8e4cf1f7a64fa4df43"),
        ObjectId("5c947e944cf1f7a64fa4df44"),
        ObjectId("5c947e9d4cf1f7a64fa4df45"),
        ObjectId("5c947ea44cf1f7a64fa4df46"),
        ObjectId("5c947ebd4cf1f7a64fa4df47")
    ]
}

Display all documents from the collection ?

db.castingDemo.find();
{ "_id": ObjectId("5c947e874cf1f7a64fa4df42"), "Amount": "200" }
{ "_id": ObjectId("5c947e8e4cf1f7a64fa4df43"), "Amount": "100" }
{ "_id": ObjectId("5c947e944cf1f7a64fa4df44"), "Amount": "110" }
{ "_id": ObjectId("5c947e9d4cf1f7a64fa4df45"), "Amount": "95" }
{ "_id": ObjectId("5c947ea44cf1f7a64fa4df46"), "Amount": "85" }
{ "_id": ObjectId("5c947ebd4cf1f7a64fa4df47"), "Amount": "75" }

Example: Casting String to Number

Here is the query that automatically converts from string to number using JavaScript comparison ?

db.castingDemo.find("this.Amount > 85");
{ "_id": ObjectId("5c947e874cf1f7a64fa4df42"), "Amount": "200" }
{ "_id": ObjectId("5c947e8e4cf1f7a64fa4df43"), "Amount": "100" }
{ "_id": ObjectId("5c947e944cf1f7a64fa4df44"), "Amount": "110" }
{ "_id": ObjectId("5c947e9d4cf1f7a64fa4df45"), "Amount": "95" }

How It Works

The JavaScript expression "this.Amount > 85" uses the $where operator internally, which allows JavaScript evaluation. During comparison, JavaScript automatically converts the string values to numbers, enabling numeric comparison even though the field contains string data.

Conclusion

MongoDB supports type casting through JavaScript expressions using the $where operator. This allows automatic conversion from strings to numbers during query evaluation, enabling numeric comparisons on string fields.

Updated on: 2026-03-15T00:21:19+05:30

381 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements