$type
The $type aggregation operator returns the BSON data type of a specified field. This is useful for identifying the data type of field values during aggregation operations.
Parameters
-
expression: The field or expression whose type to return.
Example (MongoDB Shell)
The following example demonstrates using the $type operator to identify the data type of the price field for each product.
Create sample documents
db.inventory.insertMany([ { _id: 1, item: "Notebook", price: 15.99 }, { _id: 2, item: "Pen", price: "2.50" }, { _id: 3, item: "Eraser", price: 1 }, { _id: 4, item: "Ruler", price: null } ]);
Query example
db.inventory.aggregate([ { $project: { item: 1, price: 1, priceType: { $type: "$price" } } } ]);
Output
[
{ _id: 1, item: 'Notebook', price: 15.99, priceType: 'double' },
{ _id: 2, item: 'Pen', price: '2.50', priceType: 'string' },
{ _id: 3, item: 'Eraser', price: 1, priceType: 'int' },
{ _id: 4, item: 'Ruler', price: null, priceType: 'null' }
]
Code examples
To view a code example for using the $type aggregation operator, choose the tab for the language that you want to use: