简体   繁体   中英

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.

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM