w3resource

How to Display all Documents from every Collection in MongoDB

MongoDB: Display all Documents from all Collections

In MongoDB, you can view the contents of each collection within a database by iterating over all collections and retrieving their documents. This process is especially useful for database exploration and debugging.

Syntax and Approach:

MongoDB doesn’t directly provide a single command to view all contents across all collections, so you’ll need to:

  • Retrieve the names of all collections.
  • Use find() on each collection to display its documents.

Example:

Here's an example using JavaScript in the MongoDB shell to show the contents of all collections.

Code:

// Connect to the database
const db = db.getSiblingDB("yourDatabaseName");  // Replace with your database name

// Get all collection names in the database
const collections = db.getCollectionNames();

// Loop through each collection name and show its contents
collections.forEach(collectionName => {
   // Log the collection name
   print("Contents of Collection: " + collectionName);
   
   // Show all documents in the collection
   db[collectionName].find().forEach(doc => printjson(doc));
});

Explanation:

  • const db = db.getSiblingDB("yourDatabaseName"):
    • Connects to the specified database. Replace "yourDatabaseName" with the actual name of your MongoDB database.
  • const collections = db.getCollectionNames():
    • Retrieves all collection names in the database and stores them in an array called collections.
  • collections.forEach(collectionName => { ... }):
    • Loops through each collection name in the collections array.
  • print("Contents of Collection: " + collectionName):
    • Logs the name of the current collection to indicate which collection's contents are being displayed.
  • db[collectionName].find().forEach(doc => printjson(doc)):
    • Uses find() to retrieve all documents in the current collection.
    • The forEach() method is applied to print each document in JSON format using printjson().

This code snippet will print the name of each collection followed by the documents within it. It’s a useful approach for inspecting all data in a database without manually querying each collection.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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/mongodb-display-all-documents-from-all-collections.php