sam
sam

Reputation: 33

How can I get all mongoDB collection names using Node.js code?

I want to store all collection names of MongoDB in a variable/array. How can I write nodeJS code to do that?

Upvotes: 2

Views: 3503

Answers (2)

lefrost
lefrost

Reputation: 581

await db.listCollections().toArray().map(c => c.name);

This returns a string array containing the name of every collection.

Upvotes: -1

Sohail
Sohail

Reputation: 597

  1. create a connection by providing connection url.
  2. create a client to db using database name client.db(dbName);
  3. call listCollections method to get detail info of each collection.
  4. finally filter and push the required information and close the connection.

    const mongo = require('mongodb').MongoClient;
    mongo.connect(connectionUrl, function(err, client) {
    let allCollections = [];
    //create client by providing database name
    const db = client.db(dbName);
    db.listCollections().toArray(function(err, collections) {
        if(err) console.log(err);
        //iterate to each collection detail and push just name in array
        collections.forEach(eachCollectionDetails => {
            allCollections.push(eachCollectionDetails.name);
        });
        //close client
        client.close();
     });
    });
    

Upvotes: 4

Related Questions