How to check if field is a number in MongoDB?

To check if a field is a number in MongoDB, use the $type operator with the value "number". This operator matches documents where the specified field contains numeric values (integers, doubles, or decimals).

Syntax

db.collectionName.find({fieldName: {$type: "number"}});

Sample Data

Let us create a collection with documents containing different data types ?

db.checkIfFieldIsNumberDemo.insertMany([
    {"StudentName": "John", "StudentAge": 23},
    {"StudentName": "Chris", "StudentMathScore": 98, "StudentCountryName": "US"},
    {"StudentName": "Robert", "StudentCountryName": "AUS"},
    {"StudentId": 101, "StudentName": "Larry", "StudentCountryName": "AUS"}
]);
{
   "acknowledged": true,
   "insertedIds": [
      ObjectId("5c9ec75dd628fa4220163b83"),
      ObjectId("5c9ec77cd628fa4220163b84"),
      ObjectId("5c9ec7a4d628fa4220163b85"),
      ObjectId("5c9ec7ccd628fa4220163b86")
   ]
}

Display all documents to see the data structure ?

db.checkIfFieldIsNumberDemo.find();
{
   "_id": ObjectId("5c9ec75dd628fa4220163b83"),
   "StudentName": "John",
   "StudentAge": 23
}
{
   "_id": ObjectId("5c9ec77cd628fa4220163b84"),
   "StudentName": "Chris",
   "StudentMathScore": 98,
   "StudentCountryName": "US"
}
{
   "_id": ObjectId("5c9ec7a4d628fa4220163b85"),
   "StudentName": "Robert",
   "StudentCountryName": "AUS"
}
{
   "_id": ObjectId("5c9ec7ccd628fa4220163b86"),
   "StudentId": 101,
   "StudentName": "Larry",
   "StudentCountryName": "AUS"
}

Example: Check for Numeric Fields

Find documents where StudentMathScore is a number ?

db.checkIfFieldIsNumberDemo.find({StudentMathScore: {$type: "number"}});
{
   "_id": ObjectId("5c9ec77cd628fa4220163b84"),
   "StudentName": "Chris",
   "StudentMathScore": 98,
   "StudentCountryName": "US"
}

More Examples

Check for any document with numeric StudentAge field ?

db.checkIfFieldIsNumberDemo.find({StudentAge: {$type: "number"}});

Find all documents containing any numeric field using $or operator ?

db.checkIfFieldIsNumberDemo.find({
    $or: [
        {StudentAge: {$type: "number"}},
        {StudentId: {$type: "number"}},
        {StudentMathScore: {$type: "number"}}
    ]
});

Conclusion

The $type operator with "number" efficiently identifies documents containing numeric fields. It matches integers, doubles, and decimal values, making it useful for data validation and filtering operations.

Updated on: 2026-03-15T00:40:25+05:30

602 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements