Listing all collections in a mongo database within a nodejs script
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 url
var 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());
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: {} }
});