1

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.

Ashu Grover
  • 737
  • 1
  • 11
  • 26
  • Possible duplicate of [MongoDB query multiple collections at once](https://stackoverflow.com/questions/6502541/mongodb-query-multiple-collections-at-once) – Molda Dec 13 '18 at 16:32

1 Answers1

2

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());
}
eerFun
  • 145
  • 8
  • Thank you, this set me up in the right direction, I used listCollections() instead of getCollectionNames() though, the latter is deprecated... – Ashu Grover Dec 28 '18 at 14:41