$type aggregation operator in MongoDB - To display type of the field in document

You are here : Home / MongoDB Tutorial



Contents of page >
  • $type aggregation operator
  • 1) First let's create insert documents in collection in MongoDB
  • 2) Now, Write query which display type of field “name” >

$type aggregation operator
$type aggregation operator returns the type of the field in document.

1) First let's create insert documents in collection in MongoDB

1.1) Let's create new collection and insert document in it before finding >
We will insert values of different type in document.
db.testColl.insert( { _id: 1, name :  "ankit" })  //string

db.testColl.insert({ _id: 2, name  : 11 }) //double
db.testColl.insert( { _id: 3, name : NumberLong(12) }) //long

db.testColl.insert({ _id: 4, name : [ 21, 21.2 ] }) //array
db.testColl.insert( { _id: 5, name : {city: "delhi"} } ) //object

db.testColl.insert({ _id: 6 }) //missing
Above will create collection (or table) (if collection already exists it will insert documents in it).

1.2) Let’s query all documents of collection using find() method>
> db.testColl.find()
Output>
{ "_id" : 1, "name" : "ankit" }
{ "_id" : 2, "name" : 11 }
{ "_id" : 3, "name" : NumberLong(12) }
{ "_id" : 4, "name" : [ 21, 21.2 ] }
{ "_id" : 5, "name" : { "city" : "delhi" } }
{ "_id" : 6 }



2) Now, Write query which display type of field “name” >

We will use $type operator.
db.testColl.aggregate([{
   $project: {
      typeOf_name : { $type: "$name" }
   }
}])

Note :  $type can be used in MongoDB 3.4 or above.


Summary -
So in this MongoDB tutorial we learned about $type aggregation operator in MongoDB - To display type of the field in document



Having any doubt? or you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter. You may join our fbGroup or linkedInGroup as well.



RELATED LINKS>

What is MongoDB - A quick introduction to database


eEdit
Must read for you :