How to find datatype of all the fields in Mongo
Asked Answered
A

3

9

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/

Asphyxiate answered 19/2, 2016 at 11:8 Comment(0)
S
10
> db.test.findOne()
{ "_id" : NumberLong(1), "gender" : "M", "vip" : false }
> db.test.findOne().gender
M
> typeof db.test.findOne().gender
string
Shinto answered 19/2, 2016 at 20:21 Comment(0)
A
6

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
Anthropography answered 17/10, 2018 at 10:22 Comment(2)
these are javascript representation of types not actual mongodb typesWorcester
In the command prompt (mongo prompt) it works like a charm. Splendid!!Sardinian
P
1

You can for example query the type of gender field:

typeof db.getCollection('your_collection').findOne({"_id": NumberLong(1)}).gender
Pied answered 19/2, 2016 at 20:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.