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
Using python. Returns the set of all top-level keys in the collection:
To get a list of all the keys minus
_id
, consider running the following aggregate pipeline:I think the best way do this as mentioned here is in mongod 3.4.4+ but without using the
$unwind
operator and using only two stages in the pipeline. Instead we can use the$mergeObjects
and$objectToArray
operators.In the
$group
stage, we use the$mergeObjects
operator to return a single document where key/value are from all documents in the collection.Then comes the
$project
where we use$map
and$objectToArray
to return the keys.Now if we have a nested documents and want to get the keys as well, this is doable. For simplicity, let consider a document with simple embedded document that look like this:
The following pipeline yield all keys (field1, field2, field3, field4).
With a little effort, we can get the key for all subdocument in an array field where the elements are object as well.
Here is the sample worked in Python: This sample returns the results inline.
I was trying to write in nodejs and finally came up with this:
After reading the newly created collection "allFieldNames", delete it.
A cleaned up and reusable solution using pymongo:
Usage: