Wednesday, September 3, 2014

Get Schema from your Collection on MongoDB

     

      
        As I'm preparing a M101J: MongoDB for Java Developers, and now it's my fifth week within, however I've encountered a problem during the assignment of the week, and it was about how to get the keys (Fields) of a collection (of course if it has one schema for all his documents, and not different one), because even if you perform the function findOne(), you can't find out what's exactly the schema and especially if the retrieved document has a bunch of data (Like the one that is delivered for the assignment) and it'll be hard to distinct the keys from the data....Just I want to notice that mongoDB use JSON format to store data.
So one of the solution is using JavaScript in mongo shell to get your keys out, and you should execute the following code (don't forget to change the collection name !!) :

> myKeys = db.myCollection.findOne();
> for (var key in myKeys) {print(key);}


But if you want also know what's the type of each key (field), your can replace the second command by the following 

> for (var key in myKeys) {print(key + " ==> " + myKeys[key]);}

    That's all, just remember in this solution we suppose that the collection has unique schema because if not you will not get a relevant result!