0

I'm trying to print the first document of each collection in my db. I have the following script:

var collectionNames = db.getCollectionNames();
for(var i = 0, len = collectionNames.length; i < len ; i++){
    db[collectionNames[i]].findOne() //find[0]
}

I don't see where is the error in my logic but this code only prints the first document from the latest collection

glytching
  • 44,936
  • 9
  • 114
  • 120
M. Joe
  • 13
  • 3

1 Answers1

0

Say that we have

> db.test1.save({item: 1})
WriteResult({ "nInserted" : 1 })
> db.test1.save({item: 2})
WriteResult({ "nInserted" : 1 })
> db.test1.save({item: 3})
WriteResult({ "nInserted" : 1 })
> db.test2.save({item: 3})
WriteResult({ "nInserted" : 1 })
> db.test2.save({item: 4})
WriteResult({ "nInserted" : 1 })

Then we can run:

>var docs = [];
>
> collectionNames.forEach(function(name){
... docs.push(db[name].findOne());
... });

Then we can print docs

> docs
[
        {
                "_id" : ObjectId("59fc9754cb24a8fbf29c6d5a"),
                "item" : 1
        },
        {
                "_id" : ObjectId("59fc9762cb24a8fbf29c6d5d"),
                "item" : 3
        }
]

The reason why db[collectionNames[i]].findOne() does not work in your example is that your doing nothing with the return value.

Kevin Smith
  • 13,746
  • 4
  • 52
  • 77