Ashu Grover
Ashu Grover

Reputation: 767

Fetch all documents of a database in MongoDB using nodejs

Iam new to both MongoDB and nodejs. I have a requirement under which I need to fetch all the documents in a DB of mongo. I have found many codes which let me fetch all docs from a collection in DB but no code to fetch all docs of DB in one go. Can cursors be used for this? Following is the code I found:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:port/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  dbo.collection("customers").find({}).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });
});

I want to fetch all docs under "mydb", not only the ones under collection "customers". The final output should be a JSON containing documents JSONs in it.

Note: All documents under multiple collections of "mydb" are in same json format.

Upvotes: 1

Views: 842

Answers (1)

eerFun
eerFun

Reputation: 143

You have to query separately on each collection and concatenate them together, what do you think about something like this:

var dataFromAllCollections = [];
const collections = db.getCollectionNames();
for(var i = 0; i< collections.length; i++){    
   dataFromAllCollections.concat(db.getCollection(collections[i]).find());
}

Upvotes: 2

Related Questions