如何在Mongo shell中列出所有的数据库?

332
我知道如何在特定数据库中列出所有集合,但是如何在MongoDB shell中列出所有可用的数据库呢?
8个回答

438

使用命令show dbs可以在mongoDB控制台中列出所有数据库。

有关mongo shell命令的更多信息,请参阅Mongo Shell快速参考


40
对于像我这样刚安装了MongoDB的人,可能会困惑于运行 db 命令后显示当前数据库是 test,但在本页面的任何命令中都找不到它。这个问题在这里得到了解释:https://dev59.com/hlkT5IYBdhLWcg3wWONA - Martin Smith
3
你怎么才能到达那里呢:/ - Jamie Hutber
3
在命令行中输入mongo(或在mongo --nodb中不连接到数据库)会让你感到很迷茫。 - magikMaker
1
是的,我不得不来这里寻找像 show dbs 这样简单的命令,因为当我去文档中查找时,根本找不到 show dbs 命令。有时候,“文档”真的很让人沮丧。 - MadHatter
2
该命令在 --eval 中不起作用,只能在交互式 shell 中使用。这个答案的选项确实可行(输出格式不同)。https://dev59.com/8F8e5IYBdhLWcg3wPIaA#32192253 - Gert van den Berg
当我在 Red Hat OpenShift 的 MongoDB Pod 终端中运行时,会出现以下错误信息:"errmsg" : "not authorized on admin to execute command { listDatabases: 1.0, $db: "admin" }"。 - user1063287

96

对于数据库清单:

show databases
show dbs

表/集合列表:

show collections
show tables
db.getCollectionNames()

67

对于 MongoDB shell 版本 3.0.5,请在 shell 中插入以下命令:

db.adminCommand('listDatabases')
或者,另一种选择是:
db.getMongo().getDBNames()

7
如果你处于"自我封闭"状态,只需要数据库名称:mongo admin --quiet -u <mongodb_admin> -p [<password>] --eval 'db.getMongo().getDBNames().forEach(function(db){print(db)})' 希望能对你有所帮助。 - Boop

48

从命令行发出命令

mongo --quiet --eval  "printjson(db.adminCommand('listDatabases'))"

它会输出结果

{
    "databases" : [
        {
            "name" : "admin",
            "sizeOnDisk" : 978944,
            "empty" : false
        },
        {
            "name" : "local",
            "sizeOnDisk" : 77824,
            "empty" : false
        },
        {
            "name" : "meteor",
            "sizeOnDisk" : 778240,
            "empty" : false
        }
    ],
    "totalSize" : 1835008,
    "ok" : 1
}

要获取所有数据库的垂直列表以进行下游处理,请执行以下操作

mongo --quiet --eval  "printjson(db.adminCommand('listDatabases'))" | jq  '.databases[].name' | tr -d '"' 

这将输出以下内容,列出所有数据库

admin
local
meteor

2
最佳解决方案是在不需要先进入Mongo shell模式的情况下运行自动化程序。 - herm
基于这个答案,我想到了以下代码来列出所有数据库并按大小排序,最后显示总大小:listDatabases="$(mongo --quiet --eval "printjson(db.adminCommand('listDatabases'))")"; ( while IFS=$'\t' read -r size name; do printf '%s\t%s\n' "$name" "$(numfmt --to=iec <<<"$size")"; done < <(jq -r '.databases[] | [.sizeOnDisk, .name] | @tsv' <<<"$listDatabases" | sort -rn); printf -- '-\t-\n'; printf "TOTAL\t%s\n" "$(jq -r .totalSize <<<"$listDatabases" | numfmt --to=iec)" ) | column -t -s$'\t' - Paul Tobias

19

列出MongoDB数据库的Shell命令

 show databases     //Print a list of all available databases.
 show dbs   // Print a list of all databases on the server.

更多基础命令

use <db>    // Switch current database to <db>. The mongo shell variable db is set to the current database.
show collections    //Print a list of all collections for current database.
show users  //Print a list of users for current database.
show roles  //Print a list of all roles, both user-defined and built-in, for the current database.

10

有几个命令可用于在MongoDB shell中列出所有数据库。

首先,使用'mongo'命令启动Mongodb shell。

mongo

然后使用以下任一命令来列出所有数据库。

  • show dbs(显示所有可用数据库的列表)
  • show databases(同上)
  • db.adminCommand({ listDatabases: 1, nameOnly: true } )(以名称方式列出所有数据库)

一个快照

有关更多详细信息,请查看此处

谢谢。


2
根据MongoDB官方文档,对于MongoDB 4+,您可以仅通过在admin数据库上运行db.adminCommand( { listDatabases: 1, , nameOnly: true } )来列出数据库名称。
如果您使用的是MongoDB Cloud,则需要先连接到您的MongoDB部署。在这种情况下,您可以在终端中运行此命令mongosh "mongodb+srv://cluster0.<your-connection-string>.mongodb.net" --apiVersion 1 --username <your-user-name>

Atlas atlas-xxxxxx-shard-0 [primary] test> db.adminCommand({listDatabases:1 , nameOnly: true})
{
  databases: [
    { name: 'sample_airbnb' },
    { name: 'sample_analytics' },
    { name: 'sample_geospatial' },
    { name: 'sample_guides' },
    { name: 'sample_mflix' },
    { name: 'sample_restaurants' },
    { name: 'sample_supplies' },
    { name: 'sample_training' },
    { name: 'sample_weatherdata' },
    { name: 'admin' },
    { name: 'local' }
  ],
  ok: 1,
  '$clusterTime': {
    clusterTime: Timestamp({ t: xxxxxxxxxx, i: 1 }),
    signature: {
      hash: Binary(Buffer.from("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "hex"), 0),
      keyId: Long("xxxxxxxxxxxxx")
    }
  },
  operationTime: Timestamp({ t: xxxxxxxxxx, i: 1 })
}


1

我找到了一个解决方案,其中admin() / others没有起作用。

const { promisify } = require('util');
const exec = promisify(require('child_process').exec)
async function test() {
  var res = await exec('mongo  --eval "db.adminCommand( { listDatabases: 1 }         
)" --quiet')
  return { res }
}

test()
  .then(resp => {
    console.log('All dbs', JSON.parse(resp.res.stdout).databases)
  })
test()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接