Listing all collections in a mongo database within a nodejs script
In the 2.0 version of the MongoDB driver for node.js you can use listCollections
to get a cursor that contains the information of all collections. You can then call toArray
on the cursor to retrieve the info.
db.listCollections().toArray(function(err, collInfos) { // collInfos is an array of collection info objects that look like: // { name: 'test', options: {} }});
Here is a full example on how you do it with the 3.4 version of the Mongo driver for node
const MongoClient = require("mongodb").MongoClient;// Connection urlvar url = 'mongodb://localhost:27017/test';const client = new MongoClient(url, { useUnifiedTopology: true }); // { useUnifiedTopology: true } removes connection warnings;const dbName = "test";client .connect() .then( client => client .db(dbName) .listCollections() .toArray() // Returns a promise that will resolve to the list of the collections ) .then(cols => console.log("Collections", cols)) .finally(() => client.close());
If you have access to async/await
, it is much cleaner to promisify toArray
on the iterator and not use a callback.
static toArray(iterator) { return new Promise((resolve, reject) => { iterator.toArray((err, res) => { if (err) { reject(err); } else { resolve(res); } }); });}
const myArray = await toArray(db.listCollections());