MongoDB Show all contents from all collections

477,246

Solution 1

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.

Solution 2

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.

Solution 3

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
}

Solution 4

This way:

db.collection_name.find().toArray().then(...function...)

Solution 5

This will do:

db.getCollectionNames().forEach(c => {
    db[c].find().forEach(d => {
        print(c); 
        printjson(d)
    })
})
Share:
477,246

Related videos on Youtube

Reno
Author by

Reno

Updated on July 08, 2022

Comments

  • Reno
    Reno almost 2 years

    Is it possible to show all collections and its contents in MongoDB?

    Is the only way to show one by one?

  • imbatman
    imbatman about 7 years
    Please state this as the correct answer. You can only view ALL content from ALL collections by writing code, not querying via cli
  • Steven Ventimiglia
    Steven Ventimiglia over 6 years
    If you need to visually tidy up the collection presented to you, I also recommend: db.collectionName.find().pretty()
  • t-bone
    t-bone about 5 years
    Keep in mind this doesn't work if you have certain characters (like a hyphen) in the collection name. In that case use db["collection-name"].find()
  • hallman76
    hallman76 over 4 years
    Use count() instead of find(): db.getCollectionNames().map( (name) => ({[name]: db[name].count()}) )
  • jjwallace
    jjwallace over 4 years
    Best solution, shows the contents of my collection!
  • Bilaal Abdel Hassan
    Bilaal Abdel Hassan over 2 years
    Thanks @Bossan for the clarification. Helped a lot.