Listing all collections in a mongo database within a nodejs script

38,907

Solution 1

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: {} }
});

Solution 2

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

Solution 3

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());
Share:
38,907
Jake
Author by

Jake

Updated on April 02, 2021

Comments

  • Jake
    Jake about 3 years

    I have found a few answers for listing collections in the shell but all the answers I have found for listing collections in a nodejs script seem to have been deprecated, answers like collectionNames and moongose.connection.db return has no method.