Is there any way by which we can fetch the field(Column name) of a collection in MongoDb. Like we have in mysql as follows:
SHOW columns FROM table_name
Or any way to check if a particular field exists in a collection.
First question no, as each doc in a collection is independent; second question yes (using $exists
):
# Get the count of docs that contain field 'fieldname'
db.coll.find({'fieldname': {'$exists': 1}}).count()
In MongoDB every entry can contain a different number of fields, as well as different field names, too. That's why such a command is not there in the Mongo APIs: in MySQL you can do it because every row will have the same number of column and same column names. In MongoDB wou cannot make this assumption. What you can do is to check if a field is there in the retrieved document simply by:
if field_name in doc:
# Do stuff.
where field_name
is the "column" name you want to check existence and doc is the current doc
pointed by the cursor. Remember that doc
is a dict, so you can treat it as you would treat any other dict in Python.
Since each document is separate from the other there is no easy way to do this, however, if you wish to understand what you have in your collection you can use Variety as described here:
http://blog.mongodb.org/post/21923016898/meet-variety-a-schema-analyzer-for-mongodb
It basically Map Reduces your collection to find out what fields you have in it.
As @JohnnyHK said, you can check the existance of a field by using $exists
: http://docs.mongodb.org/manual/reference/operator/exists/
This is not best practices but in the shell you can type
Object.keys(db.posts.findOne())
Note: this doesnt show you the inner keys in the object, you can use map reduce to resolve this but if your object is simple this pretty much does the task.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With