MongoDB查看所有数据库命令
在MongoDB中,可以使用一些命令来查看所有的数据库。这些命令可以帮助我们了解当前MongoDB服务器上存在的数据库,以及它们的一些基本信息。本文将介绍几个常用的命令,并提供相应的代码示例。
1. show dbs
show dbs
命令用于显示MongoDB服务器上的所有数据库。这些数据库包括系统默认的数据库(如admin、config和local),以及用户创建的数据库。该命令将返回所有数据库的列表,并显示它们的大小。
```shell
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
testDB 0.000GB
```mermaid
erDiagram
DATABASE MongoDB {
"admin" -- "system.users" : Contains user information
"config" -- "system.sessions" : Contains session information
"local" -- "startup_log" : Contains server startup logs
"testDB" -- "collection1" : Contains collection1 data
}
2. use db
在MongoDB中,要使用一个数据库,你需要使用use
命令切换到该数据库。use db
命令将数据库切换为指定的数据库,并返回switched to db db
的消息,其中db是你切换到的数据库名。
```shell
> use testDB
switched to db testDB
## 3. db
`db`命令用于查看当前正在使用的数据库。它将返回当前数据库的名称。
```markdown
```shell
> db
testDB
## 4. db.stats()
`db.stats()`命令用于获取当前数据库的统计信息,如数据大小、对象数量等。它将返回一个包含这些统计信息的文档。
```markdown
```shell
> db.stats()
{
"db" : "testDB",
"collections" : 2,
"views" : 0,
"objects" : 5,
"avgObjSize" : 136.4,
"dataSize" : 682.0,
"storageSize" : 4096.0,
"numExtents" : 0,
"indexes" : 1,
"indexSize" : 4096.0,
"fileSize" : 0,
"ok" : 1.0
}
## 5. db.getCollectionNames()
`db.getCollectionNames()`命令用于获取当前数据库中的所有集合(表)的名称。它将返回一个包含这些集合名称的数组。
```markdown
```shell
> db.getCollectionNames()
[ "collection1", "collection2" ]
## 6. db.getCollectionInfos()
`db.getCollectionInfos()`命令用于获取当前数据库中的所有集合(表)的信息。它将返回一个包含这些集合信息的数组。
```markdown
```shell
> db.getCollectionInfos()
[
{
"name" : "collection1",
"type" : "collection",
"options" : {},
"info" : {
"readOnly" : false
},
"idIndex" : {
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "testDB.collection1"
}
},
{
"name" : "collection2",
"type" : "collection",
"options" : {},
"info" : {
"readOnly" : false
},
"idIndex" : {
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "testDB.collection2"
}
}
]
## 结论
通过使用上述命令,我们可以方便地查看和了解MongoDB服务器上的所有数据库。这些命令可以帮助我们管理和维护数据库,并获得有关数据库的基本信息。
希望本文对您学习和使用MongoDB有所帮助!
参考链接:
- [MongoDB官方文档](
- [MongoDB查询指南](