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
Maybe slightly off-topic, but you can recursively pretty-print all keys/fields of an object:
Useful when all objects in a collection has the same structure.
With Kristina's answer as inspiration, I created an open source tool called Variety which does exactly this: https://github.com/variety/variety
We can achieve this by Using mongo js file. Add below code in your getCollectionName.js file and run js file in the console of Linux as given below :
Thanks @ackuser
If you are using mongodb 3.4.4 and above then you can use below aggregation using
$objectToArray
and$group
aggregationHere is the working example
I have 1 simpler work around...
What you can do is while inserting data/document into your main collection "things" you must insert the attributes in 1 separate collection lets say "things_attributes".
so every time you insert in "things", you do get from "things_attributes" compare values of that document with your new document keys if any new key present append it in that document and again re-insert it.
So things_attributes will have only 1 document of unique keys which you can easily get when ever you require by using findOne()
You can use aggregation with new
$objectToArrray
in3.4.4
version to convert all top key & value pair into document arrays followed by$unwind
&$group
with$addToSet
to get distinct keys across entire collection.$$ROOT
for referencing the top level document.You can use below query for getting keys in a single document.