Listing all Collections in MongoDB Shell
How to List all Collections in MongoDB Shell
To list all collections in a MongoDB database, you can use the MongoDB shell and the show collections command or the db.getCollectionNames() method. Here’s how you can do this, with examples, syntax, and detailed explanations.
Description:
Listing all collections in a MongoDB database is a simple task that can be accomplished using either the show collections command or the db.getCollectionNames() method within the MongoDB shell. These commands provide a quick overview of all collections present in the active database.
Syntax:
Method 1: Using the show collections command:
show collections
Method 2: Using db.getCollectionNames():
db.getCollectionNames()
Example Code:
The following example shows both methods to list collections in a database named sampledb.
Code:
// Switch to the database 'sampledb'
use sampledb
// Method 1: List all collections in the current database
show collections
// Method 2: Use db.getCollectionNames() to list collections
db.getCollectionNames()
Explanation:
- use sampledb
This command changes the context to the ‘sampledb’ database, where we want to list all collections. - show collections
This command is a simple way to list all collections in the current database. It displays each collection name in the shell. - db.getCollectionNames()
This is a MongoDB method that returns an array of collection names within the current database. This method is helpful when you want to retrieve the collection names programmatically or store them for further processing.
Both commands will output the names of all collections in the ‘sampledb’ database.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/mongodb/snippets/how-to-list-all-collections-in-mongodb-shell.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics