Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (47.6k points)

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

1 Answer

0 votes
by (106k points)

For getting the name of all keys in the collection you can use 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" 

})

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
1 answer
asked Oct 5, 2019 in SQL by Tech4ever (20.3k points)
0 votes
1 answer

Browse Categories

...