Husnain Ashfaq
Husnain Ashfaq

Reputation: 142

How to get N number of documents from each collection within a DB?

I am using following shell script to get top 5 documents from every collection in DB but its returning 5 documents from last collection only.

var collections = db.getCollectionNames();
var count = 0;

for (var i = 0; i < collections.length; i++) {
  db.getCollection(collections[i]).find().limit(5).pretty();
}

Upvotes: 1

Views: 152

Answers (1)

Tiya Jose
Tiya Jose

Reputation: 1419

You can use the following query:

db.getCollectionNames().forEach(function(collectionName)
 {
   var doc = db[(collectionName)].find().limit(5);
   while ( doc.hasNext()) {
       printjson(doc.next());
   }
 });

Upvotes: 1

Related Questions