Is it possible to show all collections and its contents in MongoDB?
Is the only way to show one by one?
Once you are in terminal/command line, access the database/collection you want to use as follows:
show dbs
use <db name>
show collections
choose your collection and type the following to see all contents of that collection:
db.collectionName.find()
More info here on the MongoDB Quick Reference Guide.
var collections = db.getCollectionNames();
for(var i = 0; i< collections.length; i++){
print('Collection: ' + collections[i]); // print the name of each collection
db.getCollection(collections[i]).find().forEach(printjson); //and then print the json of each of its elements
}
I think this script might get what you want. It prints the name of each collection and then prints its elements in json.
Before writing below queries first get into your cmd or PowerShell
TYPE:
mongo //To get into MongoDB shell
use <Your_dbName> //For Creating or making use of existing db
To List All Collection Names use any one from below options :-
show collections //output every collection
OR
show tables
OR
db.getCollectionNames() //shows all collections as a list
To show all collections content or data use below listed code which had been posted by Bruno_Ferreira.
var collections = db.getCollectionNames();
for(var i = 0; i< collections.length; i++) {
print('Collection: ' + collections[i]); // print the name of each collection
db.getCollection(collections[i]).find().forEach(printjson); //and then print the json of each of its elements
}
This way:
db.collection_name.find().toArray().then(...function...)
This will do:
db.getCollectionNames().forEach(c => {
db[c].find().forEach(d => {
print(c);
printjson(d)
})
})
I prefer another approach if you are using mongo
shell:
First as the another answers: use my_database_name
then:
db.getCollectionNames().map( (name) => ({[name]: db[name].find().toArray().length}) )
This query will show you something like this:
[
{
"agreements" : 60
},
{
"libraries" : 45
},
{
"templates" : 9
},
{
"users" : 19
}
]
You can use similar approach with db.getCollectionInfos()
it is pretty useful if you have so much data & helpful as well.
count()
instead of find()
: db.getCollectionNames().map( (name) => ({[name]: db[name].count()}) )
Success story sharing
db.collectionName.find().pretty()
db["collection-name"].find()