Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return actual type of a field in MongoDB

Tags:

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?

like image 858
nikcub Avatar asked Jul 08 '10 22:07

nikcub


People also ask

How do I find the datatype of a field in MongoDB?

As described above, the $type operator works on the BSON type in MongoDB, and it offers two identifiers for each BSON type; one is “integer” and the other is “string“. For instance, to locate a Double data type, one can use integer value “1” and a string “double” to locate the Double data type in the specified field.

What type does MongoDB find return?

find() in MongoDB? The statement db. collection. find() returns the cursor of Result Set of a query by which you can iterate over the result set or print all documents.

How do I display a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

What is $type in MongoDB?

$type selects documents where the value of the field is an instance of the specified BSON type(s). Querying by data type is useful when dealing with highly unstructured data where data types are not predictable. A $type expression for a single BSON type has the following syntax: Changed in version 3.2.


1 Answers

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"  } 
like image 52
styvane Avatar answered Oct 20 '22 01:10

styvane