0 votes
in MongoDB by
How to get the names of all the keys in a MongoDB collection in MongoDB?

1 Answer

0 votes
by
For example, from this:

db.things.insert( { type : [‘dog’, ‘cat’] } );

db.things.insert( { egg : [‘cat’] } );

db.things.insert( { type : [] } );

db.things.insert( { hello : []  } );

How to get the unique keys: type, egg, hello

We 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:

Related questions

0 votes
asked Aug 26, 2019 in NoSQL by Venkatshastri
0 votes
asked Aug 26, 2019 in NoSQL by Venkatshastri
...