When working with MongoDB databases, you may encounter instances where you must fetch the list of all available collections. In this post, you will learn how to view the list of all collections in a given database using the MongoDB Shell.
Without much further ado, let’s dive in.
Method 1: Using the Show Collections Command
The most common and easy-to-use method of showing the collections in a given database is to use the SHOW COLLECTIONS command.
The command then returns all the collections in the currently selected database. Since the command returns the collections in the currently selected database, it is good to switch to your target database first.
For example, suppose we have a database called “cinema”. We can switch to it using the USE command as shown in the following:
< 'switched to db cinema'
Once switched to the target database, you can use the SHOW COLLECTIONS command to view the list of available collections.
> disney
netflix
In the given example, the database holds five collections with the list of movies and tv shows of two major providers. Keep in mind that the command returns the collections to which the current user has access. Therefore, the command does not show it if you do not have permission to access a specific collection.
Method 2: Using the SHOW TABLES Command
Another command that you can use to retrieve the names of all collections in a given database is the SHOW TABLES command. This command works very similarly to the SHOW COLLECTIONS command.
An example is shown in the following:
< disney
netflix
Method 3: Using the GetCollectionNames Function
MongoDB provides the getCollectionNames() function that allows you to view the names of the available collections of the current database. Keep in mind that the function returns only the functions to which the current user has access.
Example:
[ 'disney', 'netflix' ]
Method 4: Using the GetCollectionInfo() Function
Another function that we can use to view the available collections is the getCollectionInfo() function. This command is very similar to the getCollectionNames() function but returns the detailed information about each collections.
An example is shown in the following:
< [
{
name: 'disney',
type: 'collection',
options: {},
info: {
readOnly: false,
uuid: UUID("3112de5f-b1b8-4b4e-bdd8-8f5fd90e13eb")
},
idIndex: { v: 2, key: [Object], name: '_id_' }
},
{
name: 'netflix',
type: 'collection',
options: {},
info: {
readOnly: false,
uuid: UUID("b6c7a300-1c80-48c2-bc57-454d6853e1a3")
},
idIndex: { v: 2, key: [Object], name: '_id_' }
}
]
Conclusion
In this post, you discovered the four main methods that you can use to fetch the list of available collections in a given database using the MongoDB Shell.
Thanks for reading. Happy coding!