Return actual type of a field in MongoDB

nikcub picture nikcub · Jul 9, 2010 · Viewed 32.6k times · Source

In MongoDB, using $type, it is possible to filter a search based on if the field matches a BSON data type (see DOCS).

For eg.

db.posts.find({date2: {$type: 9}}, {date2: 1})

which returns:

{ 
    "_id" : ObjectId("4c0ec11e8fd2e65c0b010000"), 
    "date2" : "Fri Jul 09 2010 08:25:26 GMT" 
}

I need a query that will tell me what the actual type of the field is, for every field in a collection. Is this possible with MongoDB?

Answer

styvane picture styvane · Jun 26, 2016

Starting from MongoDB 3.4, you can use the $type aggregation operator to return a field's type.

db.posts.aggregate( 
    [ 
        { "$project": { "fieldType": {  "$type": "$date2"  } } } 
    ]
)

which yields:

{ 
    "_id" : ObjectId("4c0ec11e8fd2e65c0b010000"), 
    "fieldType" : "string" 
}