Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (6.1k points)
closed by

I want to list all collections of my current database which is being used by me. How to do it?

closed

4 Answers

0 votes
by (11.4k points)
 
Best answer
  1. Open the MongoDB shell by running the "mongo" command in your terminal or command prompt.
  2. Once you are in the MongoDB shell, switch to your desired database using the "use" command. For example, if your database is named "mydatabase," type: use mydatabase.
  3. To view all the collections in the current database, you can use the "show collections" command. Simply type: show collections.
  4. The MongoDB shell will then display a list of all the collections in the current database.
  5. If you prefer a more formatted output, you can use the following JavaScript code snippet in the shell: db.getCollectionNames().forEach(function(collection) { print(collection); }); This code will iterate through each collection and print its name individually. 6. After executing the command or the code snippet, you should see a list of collections in your current database, allowing you to verify the collections being used.
0 votes
by (11.7k points)
edited by

Try this out:

JavaScript (shell):

db.getCollectionNames()

For Node.js:

db.listCollections()

Non-JavaScript (shell only):

show collections

Why this is called as non-JavaScript is because:

$ mongo prodmongo/app --eval "show collections"

MongoDB shell version: 3.2.10

connecting to: prodmongo/app

2016-10-26T19:34:34.886-0400 E QUERY    [thread1] SyntaxError: missing ; before statement @(shell eval):1:5

$ mongo prodmongo/app --eval "db.getCollectionNames()"

MongoDB shell version: 3.2.10

connecting to: prodmongo/app

[

    "Profiles",

    "Unit_Info"

]

If you want to show collections output:

$ mongo prodmongo/app --eval "db.getCollectionNames().join('\n')"

MongoDB shell version: 3.2.10

connecting to: prodmongo/app

Profiles

Unit_Info

Check out our SQL Course to have a complete grip on SQL concepts.

If you want to learn MongoDB, check out this MongoDB tutorial from Intellipaat.

0 votes
by (7.8k points)
To list all collections in the MongoDB shell, open the shell, switch to your database using the "use" command, and type "show collections". Alternatively, you can use the JavaScript code snippet "db.getCollectionNames().forEach(function(collection) { print(collection); });" for a more formatted output.
0 votes
by (13k points)

Open MongoDB shell, switch to your database, and type "show collections".

Related questions

0 votes
2 answers
asked Sep 4, 2019 in SQL by Sammy (47.6k points)
0 votes
2 answers
0 votes
1 answer
0 votes
2 answers
0 votes
2 answers

Browse Categories

...