To get all the ages that are ints from records having string and int ages records, use $type. The $type in MongoDB $type selects documents where the value of the field is an instance of the specified BSON type.
Let us create a collection with documents −
> db.demo470.insertOne({"Age":23});{ "acknowledged" : true, "insertedId" : ObjectId("5e805456b0f3fa88e2279070") } > db.demo470.insertOne({"Age":"Unknown"});{ "acknowledged" : true, "insertedId" : ObjectId("5e80545cb0f3fa88e2279071") } > db.demo470.insertOne({"Age":24});{ "acknowledged" : true, "insertedId" : ObjectId("5e805461b0f3fa88e2279072") } > db.demo470.insertOne({"Age":"Not provided"});{ "acknowledged" : true, "insertedId" : ObjectId("5e80546bb0f3fa88e2279073") }
Display all documents from a collection with the help of find() method −
> db.demo470.find();
This will produce the following output −
{ "_id" : ObjectId("5e805456b0f3fa88e2279070"), "Age" : 23 } { "_id" : ObjectId("5e80545cb0f3fa88e2279071"), "Age" : "Unknown" } { "_id" : ObjectId("5e805461b0f3fa88e2279072"), "Age" : 24 } { "_id" : ObjectId("5e80546bb0f3fa88e2279073"), "Age" : "Not provided" }
Following is the query to return all ages that are ints −
> db.demo470.find( {'Age' : { $type :"number"} } );
This will produce the following output −
{ "_id" : ObjectId("5e805456b0f3fa88e2279070"), "Age" : 23 } { "_id" : ObjectId("5e805461b0f3fa88e2279072"), "Age" : 24 }