Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find datatype of all the fields in Mongo

I have a doc

{_id:NumberLong(1),gender:"M",vip:false}.

How to extract the type of individual field in Mongo with a query.. How to use typeof operator:

https://docs.mongodb.org/manual/core/shell-types/

like image 421
svs teja Avatar asked Feb 19 '16 11:02

svs teja


2 Answers

> db.test.findOne()
{ "_id" : NumberLong(1), "gender" : "M", "vip" : false }
> db.test.findOne().gender
M
> typeof db.test.findOne().gender
string
like image 60
Gijs Avatar answered Oct 11 '22 07:10

Gijs


Question title asks for all fields and answers tell how to make it with one field. Here's an all document fields approach (just change your_collection part at the beginning):

[db.your_collection.findOne()].forEach( function(my_doc) { for (var key in my_doc) { print(key + ': ' + typeof my_doc[key]) } } )

First you get an document from the collection, then convert it to an array with [] so we can apply a function with forEach, and finally in the function we iterate over the document fields to print their key and type as we want. This should output something like:

_id: object
gender: string
vip: boolean
like image 42
josemfc Avatar answered Oct 11 '22 07:10

josemfc