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
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.
To list all collections in Mongo shell, you can use the function getCollectionNames().
We can get the schema object/first document of the collection using : var schemaObj = db. users. findOne();
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
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", ...]
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