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
Try this:
I extended Carlos LM's solution a bit so it's more detailed.
Example of a schema:
Type into the console:
Run:
Output
You could do this with MapReduce:
Then run distinct on the resulting collection so as to find all the keys:
If your target collection is not too large, you can try this under mongo shell client:
As per the mongoldb documentation, a combination of
distinct
and indexes collection operations are what would return all possible values for a given key, or index:
So in a given method one could do use a method like the following one, in order to query a collection for all it's registered indexes, and return, say an object with the indexes for keys (this example uses async/await for NodeJS, but obviously you could use any other asynchronous approach):
So querying a collection with the basic
_id
index, would return the following (test collection only has one document at the time of the test):Mind you, this uses methods native to the NodeJS Driver. As some other answers have suggested, there are other approaches, such as the aggregate framework. I personally find this approach more flexible, as you can easily create and fine-tune how to return the results. Obviously, this only addresses top-level attributes, not nested ones. Also, to guarantee that all documents are represented should there be secondary indexes (other than the main _id one), those indexes should be set as
required
.