我知道如何列出一个特定的数据库中的所有集合,但我如何列出MongoDB shell中所有可用的数据库?


当前回答

根据MongoDB官方文档,对于MongoDB 4+,只有运行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 }) }

其他回答

我已经找到了一个解决方案,其中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()

在shell上列出mongodb数据库

 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.

从命令行问题

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

数据库列表:

show databases
show dbs

表格/收藏列表:

show collections
show tables
db.getCollectionNames()

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

db.adminCommand('listDatabases')

或者:

db.getMongo().getDBNames()