Return all ages records that are ints with a MongoDB query

To return all age records that are integers from a collection containing both string and integer age values, use the $type operator. The $type operator in MongoDB selects documents where the field value matches the specified BSON data type.

Syntax

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

Create Sample Data

Let us create a collection with documents containing both integer and string age values ?

db.demo470.insertMany([
    { "Age": 23 },
    { "Age": "Unknown" },
    { "Age": 24 },
    { "Age": "Not provided" }
]);
{
   "acknowledged": true,
   "insertedIds": [
      ObjectId("5e805456b0f3fa88e2279070"),
      ObjectId("5e80545cb0f3fa88e2279071"),
      ObjectId("5e805461b0f3fa88e2279072"),
      ObjectId("5e80546bb0f3fa88e2279073")
   ]
}

View All Documents

Display all documents from the collection to see the mixed data types ?

db.demo470.find();
{ "_id": ObjectId("5e805456b0f3fa88e2279070"), "Age": 23 }
{ "_id": ObjectId("5e80545cb0f3fa88e2279071"), "Age": "Unknown" }
{ "_id": ObjectId("5e805461b0f3fa88e2279072"), "Age": 24 }
{ "_id": ObjectId("5e80546bb0f3fa88e2279073"), "Age": "Not provided" }

Query for Integer Ages Only

Use $type: "number" to return only documents where the Age field contains integer values ?

db.demo470.find({ "Age": { $type: "number" } });
{ "_id": ObjectId("5e805456b0f3fa88e2279070"), "Age": 23 }
{ "_id": ObjectId("5e805461b0f3fa88e2279072"), "Age": 24 }

Conclusion

The $type operator with "number" effectively filters documents to return only those with integer age values, excluding string entries. This is useful for data validation and type-specific queries in mixed-type collections.

Updated on: 2026-03-15T03:05:24+05:30

268 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements