tags:

views:

428

answers:

2

Hi,

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

Cheers

A: 

I have not worked on mongodb. And, my answer is purely based on some understanding (watching a dnrtv show) and little bit of documentation reading, after your question.

I don't think, mongodb provides a way for you to do such a thing primarily because it is a schema free database. You will have to figure out objects such as Cursor that is returned by find & related methods. And then see what methods are available on Cursor, traverse through each of the row, which could return some kind of an object, look at the members of such an object

for (var member in row) { print(member); }

Not sure, if this helps you at all.

shahkalpesh
+3  A: 

You could do this with MapReduce:

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

Then run distict on the resulting collection to find all of the keys:

> db[mr.result].distinct("_id")
["foo", "bar", "baz", "_id", ...]
kristina
Hi there! I've just posted a follow-up to this question asking how to make this snippet work even with keys located at deeper levels into the data structure (http://stackoverflow.com/questions/2997004/using-map-reduce-for-mapping-the-properties-in-a-collection).
And