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


当前回答

在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.

其他回答

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

有关mongo shell命令的更多信息,请参阅mongo 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 }) }

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

db.adminCommand('listDatabases')

或者:

db.getMongo().getDBNames()

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