How do I describe a collection in Mongo?

Viewed 85685

So this is Day 3 of learning Mongo Db. I'm coming from the MySql universe...

A lot of times when I need to write a query for a MySql table I'm unfamiliar with, I would use the "desc" command - basically telling me what fields I should include in my query.

How would I do that for a Mongo db? I know, I know...I'm searching for a schema in a schema-less database. =) But how else would users know what fields to use in their queries?

Am I going at this the wrong way? Obviously I'm trying to use a MySql way of doing things in a Mongo db. What's the Mongo way?

13 Answers

This is an incomplete solution because it doesn't give you the exact types, but useful for a quick view.

const doc = db.collectionName.findOne();
for (x in doc) {
  print(`${x}: ${typeof doc[x]}`)
};

Consider you have collection called people and you want to find the fields and it's data-types. you can use below query

function printSchema(obj) {
    for (var key in obj) {
        print( key, typeof obj[key]) ;
    }
};

var obj = db.people.findOne();
printSchema(obj)

The result of this query will be like below, enter image description here

Related