Tuesday 8 June 2021

MongoDB: How to find the schema of a document in the collection?

Below snippet print the schema of a document.

function printDocumentSchema(doc, indent) {
    for (var key in doc) {
        if(typeof doc[key] == "function"){   
        	continue;
        }  
           
        print(indent, key, typeof doc[key]) ;    
        
        if (typeof doc[key] == "object") {            
        	printSchema(doc[key], indent + "\t");
        }
    }
};

 

Let’s try with an example.

 

Step 1: Insert some data into the collection.

> db.employee.insert({"empId": NumberInt(1), "name": "Krishna", "hobbies" : ["trekking"], "address" : {"city": "Bangalore", "country": "India"}})
WriteResult({ "nInserted" : 1 })

 

Step 2: Get the reference of document.

> doc = db.employee.findOne()
{
	"_id" : ObjectId("60bf9cc88d62325981fe3ca8"),
	"empId" : 1,
	"name" : "Krishna",
	"hobbies" : [
		"trekking"
	],
	"address" : {
		"city" : "Bangalore",
		"country" : "India"
	}
}

Step 3: Define printDocumentSchema function.

function printDocumentSchema(doc, indent) {
    for (var key in doc) {
        if(typeof doc[key] == "function"){   
        	continue;
        }  
           
        print(indent, key, typeof doc[key]) ;    
        
        if (typeof doc[key] == "object") {            
        	printDocumentSchema(doc[key], indent + "\t");
        }
    }
};

> function printDocumentSchema(doc, indent) {
...     for (var key in doc) {
...         if(typeof doc[key] == "function"){   
...         continue;
...         }  
...            
...         print(indent, key, typeof doc[key]) ;    
...         
...         if (typeof doc[key] == "object") {            
...         printDocumentSchema(doc[key], indent + "\t");
...         }
...     }
... };


Step 4: Call ‘printDocumentSchema’ function with doc as argument.

> printDocumentSchema(doc, "  ")
   _id object
  	 str string
  	 isObjectId boolean
   empId number
   name string
   hobbies object
  	 0 string
   address object
  	 city string
  	 country string


 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment