How to view all databases in MongoDB
The way to view all databases in MongoDB is to enter the command "show dbs". 1. This command displays only non-empty databases. 2. You can switch the database through the "use" command and insert data to display it. 3. Pay attention to internal databases such as "local" and "config". 4. When using the driver, you need to use the "listDatabases()" method to obtain detailed information. 5. The "db.stats()" command can view detailed database statistics.
The way to view all databases in MongoDB is actually very simple, but it's just the tip of the iceberg. Let's explore this topic in depth and share some of my own experiences and tips when using MongoDB.
To view all databases in MongoDB, you just need to enter a simple command in the MongoDB shell:
show dbs
This command lists all available databases. But do you know? It is not enough to just know this command, we need to have a deeper understanding of why this command is so useful and some of the problems that may be encountered in actual use.
First, when you execute show dbs
, MongoDB displays all non-empty databases. This means that if you create a database but don't insert any data, it won't show up in the list. This can cause some confusion when you manage multiple projects or environments because you may think that a certain database does not exist. One way to solve this problem is to use the use
command to switch to the database you think exists and insert a record so that it will be displayed in show dbs
.
use myDatabase db.myCollection.insertOne({ test: "data" })
When using show dbs
, you may notice that some database names look weird, such as those with .
These are usually databases used internally by MongoDB, such as local
and config
. Understanding the role of these databases can help you better manage and optimize your MongoDB instances.
Another thing to note is that the show dbs
command is actually a secondary command of the MongoDB shell, not a command from the MongoDB server itself. This means that if you interact with MongoDB through a driver or API, you need to use a different approach to get the database list. For example, in MongoDB's Node.js driver, you can do this:
const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017'; MongoClient.connect(url, function(err, client) { if (err) throw err; const adminDb = client.db().admin(); adminDb.listDatabases().then(function(dbs) { console.log(dbs.databases); client.close(); }); });
This method will return an object containing all database information, including not only the database name, but also the database size and other information, which will be more useful in some cases than show dbs
.
In actual use, I found a common misunderstanding that show dbs
will display the details of all databases. Actually, it's just a simple list. If you need more information, such as the size of the database, storage engine, etc., you need to use db.stats()
command.
use myDatabase db.stats()
This command will return detailed statistics of the current database, including data size, index size, etc., which is very useful for performance optimization and resource management.
Finally, share a tip: If you often need to view a database list of multiple MongoDB instances, you can write a simple script to automate the process. This not only saves time, but also reduces manual operation errors.
const MongoClient = require('mongodb').MongoClient; async function listDatabases(url) { const client = await MongoClient.connect(url); const adminDb = client.db().admin(); const dbs = await adminDb.listDatabases(); console.log(`Databases in ${url}:`); dbs.databases.forEach(db => console.log(db.name)); await client.close(); } const urls = ['mongodb://localhost:27017', 'mongodb://anotherhost:27017']; urls.forEach(url => listDatabases(url).catch(console.error));
This script can traverse multiple MongoDB instances and list the databases in each instance, which is very convenient.
Overall, show dbs
is a very basic but useful command, but to really master the use of MongoDB, you need to know more details and techniques. Hope these sharing can help you better use MongoDB.
The above is the detailed content of How to view all databases in MongoDB. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Binance is the world's largest cryptocurrency exchange. With its huge transaction depth, rich business ecosystem and high liquidity, it provides all-round services such as spot, contracts, financial management and BNB Chain public chains. At the same time, it strives to ensure the security of user assets and promote transparent development through multiple security measures and compliance efforts.

Directory What is SatLayer What is SLAY Token SatLayer(SLAY) Airdrop SatLayer(SLAY) Price Forecast SatLayer CubeSatLayerAcesBabylon SatLayerSatLayer Roadmap SatLayer is leading the trend of Bitcoin re-staking, expanding practicality and providing sustainable returns through its Bitcoin Verification Service (BVS) mechanism. Binance Alpha will become the first SatLayer (SLAY) to go online on August 11

This article systematically sorts out the global mainstream virtual currency issuance model, including seven methods: ICO, IEO, IDO, PoW, PoS, airdrop and STO, and introduces its operating mechanism, characteristics and risks respectively. 1. Initial token issuance (ICO) is a way for the project party to raise funds by publishing a white paper to sell to the public. The threshold is low but the risk is high. 2. The initial exchange issuance (IEO) is reviewed and issued by the exchange to improve security and credibility. 3. The first decentralized exchange issuance (IDO) is conducted on a decentralized platform, emphasizing fair start-up and community participation, with high transparency but at your own risk; 4. Proof of Work (PoW) generates new blocks through computing power competition and rewards tokens to ensure network security and decentralization; 5. Proof of equity

What is the golden ratio in the catalog? From Fei's to Gold Pocket: How to show the pattern How to use gold pockets in cryptocurrency trading How to use gold pockets Why the gold ratio works in financial marketsFebonacci Gold Pocket Trading Setting Example Combined with gold pockets and other technical indicatorsCommon errors When trading gold pockets: The gold ratio is not only aesthetically valuable, but also actionable Fibonacci Gold Zone FAQ 1. What is the Fibonacci Gold Zone? 2. Why is 0.618 important in cryptocurrency trading? 3. Is the golden ratio effective? 4. How to TradingVie

Contents What is ai16z(AI16Z)? Current market conditions and price ai16zDAO’s historical factors affecting ai16z(AI16Z) price forecast 2025-20261.2025 forecast 2.2026 forecast 3.2030 forecast price forecast table (2025-2030) Conclusion ai16zDAO is a decentralized autonomous organization aimed at reshaping the venture capital operation model. Through the AI Agent, it operates as an innovative venture capital entity that combines community-driven management with transparency and efficiency of development project financing

The crypto market has seen a subtle twist this week. Bitcoin fell into consolidation around about $119,000, with volatility narrowing, while most mainstream altcoins showed a strong rebound momentum. This differentiation has attracted widespread attention: Does it indicate that funds are shifting from Bitcoin to altcoins, and the altcoin rotation market has quietly started? Although Bitcoin still firmly controls market dominance, the Altseason Index has quietly rebounded, releasing potential changes. Altcoins have generally risen, and Bitcoin has accumulated sideways and has seen significant changes in the market structure recently. Bitcoin's market dominance has declined to 58.54%, down 5.32% in 24 hours, while Ether

Coin is a native asset of its own blockchain, such as BTC and ETH, used to pay fees and incentivize networks; tokens are created based on existing blockchains (such as Ethereum) through smart contracts, representing assets, permissions or services, and relying on the host chain to operate, such as UNI and LINK, and transaction fees must be paid with ETH.

Circle, as a company with significant influence in the field of fintech, will undoubtedly have a profound impact on the entire stablecoin market. Circle is known primarily for issuing and managing stablecoins USDC, which is currently the second largest stablecoin on the market, pegged to the US dollar and aims to provide stability and reliability for digital asset transactions.
