Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get names of all keys in the collection

I'd like to get the names of all the keys in a MongoDB collection.

For example, from this:

db.things.insert( { type : ['dog', 'cat'] } ); db.things.insert( { egg : ['cat'] } ); db.things.insert( { type : [] } ); db.things.insert( { hello : []  } ); 

I'd like to get the unique keys:

type, egg, hello 
like image 622
Steve Avatar asked Feb 19 '10 19:02

Steve


People also ask

How do I get column names in MongoDB?

In MongoDB, there is no concept of columns since MongoDB is schema-less and does not contain tables. It contains the concept of collections and a collection has different types of documents to store items. db. yourCollectionName.

How do I list collections in MongoDB?

To list all collections in Mongo shell, you can use the function getCollectionNames().

How do I find the schema of a collection in MongoDB?

We can get the schema object/first document of the collection using : var schemaObj = db. users. findOne();

How do I show fields in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});


1 Answers

You could do this with MapReduce:

mr = db.runCommand({   "mapreduce" : "my_collection",   "map" : function() {     for (var key in this) { emit(key, null); }   },   "reduce" : function(key, stuff) { return null; },    "out": "my_collection" + "_keys" }) 

Then run distinct on the resulting collection so as to find all the keys:

db[mr.result].distinct("_id") ["foo", "bar", "baz", "_id", ...] 
like image 101
kristina Avatar answered Sep 24 '22 00:09

kristina