learner
learner

Reputation: 108

How do i get all keys in Mongodb collection?

I saw few solutions but those are not exact my solution. I have a DB with name results and collection name is marks like below:

db.marks.find();
{ "_id" : ObjectId("54f57522627af4bfdcf79764"), "name" : "John", "scroe1" : 23, "score2" : 21, "score5" : 12 }
{ "_id" : ObjectId("54f5761a627af4bfdcf79765"), "name" : "Mike", "scroe2" : 22, "score3" : 20, "score4" : 22 }
{ "_id" : ObjectId("559d0bc521cb2e056507c3e3"), "name" : "Bush", "score2" : 30 }

I tried with

var doc=db.marks.findOne(); for (var key in doc) print(key);

and i got

_id
name
score1
score2
score5

But i Want all keys in collection like below:

_id, name, score1, score2, score3, score4, score5

name scroe1 score2 score3here

Upvotes: 2

Views: 12347

Answers (3)

Talha Noyon
Talha Noyon

Reputation: 854

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:

db[mr.result].distinct("_id")
["foo", "bar", "baz", "_id", ...]

Upvotes: 1

Goutham P N
Goutham P N

Reputation: 65

Mongodb find() command has two arguments first one is query and second is projections.

Something like db.collection.find(query,projection).

if the document is db.myCol.find();, then it returns:

{
  {
    _id:1
    name: ''hello',
    age: 23
  }, {
    _id:2
    name: ''bollo',
    age: 27
  }
}

And db.myCol.find({},{_id:1}); returns:

1
2

Upvotes: -3

Matthew Antolovich
Matthew Antolovich

Reputation: 508

findOne will only return the first found document. Since the first document you list does not have the score3 and score4 keys, it will not display them. If you want to show all root-level keys across all documents, you would need to iterate through all the documents in the db.

var keys = [];
db.marks.find().forEach(function(doc){
    for (var key in doc){ 
        if(keys.indexOf(key) < 0){
           keys.push(key);
        }
    }
});

print(keys);

Upvotes: 4

Related Questions