How to use $type in MongoDB?

The $type operator in MongoDB selects documents where the value of a specified field matches a particular BSON type. This is useful for filtering documents based on data types rather than values.

Syntax

db.collection.find({ "field": { $type: "bsonType" } })

Where bsonType can be a string name (like "string", "number", "object") or numeric BSON type code.

Sample Data

Let's create a collection with mixed data types ?

db.demo615.insertMany([
    { "Value": 100 },
    { "Value": "100" },
    { "Value": "300" },
    { "Value": 300 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("...")
    ]
}

View All Documents

db.demo615.find();
{ "_id": ObjectId("5e99bb3465492f6c60d0027f"), "Value": 100 }
{ "_id": ObjectId("5e99bb3865492f6c60d00280"), "Value": "100" }
{ "_id": ObjectId("5e99bb3c65492f6c60d00281"), "Value": "300" }
{ "_id": ObjectId("5e99bb4265492f6c60d00282"), "Value": 300 }

Example: Find String Values Only

Query to find documents where Value field contains string data ?

db.demo615.find({ "Value": { $type: "string" } });
{ "_id": ObjectId("5e99bb3865492f6c60d00280"), "Value": "100" }
{ "_id": ObjectId("5e99bb3c65492f6c60d00281"), "Value": "300" }

Common BSON Types

Type Name Numeric Code Description
"double" 1 Double precision floating-point
"string" 2 UTF-8 string
"object" 3 Embedded document
"array" 4 Array
"int" 16 32-bit integer
"long" 18 64-bit integer

Conclusion

The $type operator is essential for type-based queries in MongoDB. Use it to filter documents by BSON data types, helping ensure data consistency and proper type handling in your applications.

Updated on: 2026-03-15T03:09:50+05:30

162 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements