2

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

2
  • 1
    You are expected to have some attempt at a solution included in your question, for people to see what your understanding of the problem is and to give them a starting point for a solution. Have a look at How to Ask and check out the tour Commented Oct 10, 2017 at 15:55
  • 1
    Possible duplicate of Listing all collections in a mongo database within a nodejs script Commented Oct 10, 2017 at 22:04

2 Answers 2

4
  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();
     });
    });
    
Sign up to request clarification or add additional context in comments.

Comments

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.