Welcome to plsql4all.blogspot.com SQL, MYSQL, ORACLE, TERADATA, MONGODB, MARIADB, GREENPLUM, DB2, POSTGRESQL.

Saturday, 3 February 2024

List all the collections in MongoDB

To list all collections in MongoDB, you can use either the MongoDB shell commands or certain MongoDB driver methods depending on the programming language you're using. Here are both methods:


Using MongoDB Shell:


1. Open MongoDB Shell:

   - Open a MongoDB shell or connect to your MongoDB server.


2. Switch to the Desired Database (Optional):

   - If you want to list collections in a specific database, switch to that database using the `use` command.

     use your_database_name


3. List Collections:

   - Use the `show collections` command to list all collections in the current database.

     show collections

   - Alternatively, you can use `db.getCollectionNames()`:

     db.getCollectionNames()


Using MongoDB Driver (e.g., in JavaScript with Node.js):


1. Connect to MongoDB:

   - Connect to MongoDB using your preferred MongoDB driver. For Node.js, you might use the `mongodb` driver.


2. List Collections:

   - Use the `listCollections` method to retrieve a cursor over the collections.

     const MongoClient = require('mongodb').MongoClient;


     const url = 'mongodb://localhost:27017'; // Replace with your MongoDB connection string

     const databaseName = 'your_database_name';


     MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, async (err, client) => {

       if (err) throw err;


       const db = client.db(databaseName);

       const collections = await db.listCollections().toArray();


       console.log('Collections:', collections.map(collection => collection.name));


       client.close();

     });

   - Replace `'your_database_name'` with the name of your database.


Choose the method that best suits your environment and preferred workflow. The MongoDB shell method is quick and easy for manual checks, while the MongoDB driver method is suitable for use within your application code.

No comments:

Post a Comment

Please provide your feedback in the comments section above. Please don't forget to follow.