30% Therapy – 40% Practice – 30% Work project

Node & MongoDB – Display Collections



To display collections of a database, you can use database.listCollections() method to get list of collections.

MongoClient.connect(url, function(error, client) {
   // Connect to the database
   const database = client.db(''myDb'');  
   // get the list of collections
   database.listCollections().toArray(function(err, collections) {
      collections.forEach(collection => console.log(collection.name));
   });
});

Example

Try the following example to create a mongodb collection −

Copy and paste the following example as mongodb_example.js −

const MongoClient = require(''mongodb'').MongoClient;
// Prepare URL
const url = "mongodb://localhost:27017/";
// make a connection to the database
MongoClient.connect(url, function(error, client) {
   if (error) throw error;
   console.log("Connected!");
   // Connect to the database
   const database = client.db(''myDb'');
   // Create the collection
   database.createCollection(''sampleCollection'');   
   database.listCollections().toArray(function(err, collections) {
      collections.forEach(collection => console.log(collection.name));
   });
   // close the connection
   client.close();
});

Output

Execute the mysql_example.js script using node and verify the output.

node mongodb_example.js
Connected!
sampleCollection
Translate »