Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to fetch all field name of collection in mongodb?

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.

like image 398
Workonphp Avatar asked Mar 05 '13 14:03

Workonphp


4 Answers

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()
like image 199
JohnnyHK Avatar answered Oct 14 '22 03:10

JohnnyHK


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.

like image 31
drekyn Avatar answered Oct 14 '22 01:10

drekyn


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/

like image 1
Sammaye Avatar answered Oct 14 '22 01:10

Sammaye


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.

like image 1
Fernando Segura Avatar answered Oct 14 '22 02:10

Fernando Segura