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?
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.
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.
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
$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.
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" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With