- Node 和 MongoDB 教程
- Node 和 MongoDB - 主页
- Node 和 MongoDB - 概述
- Node 和 MongoDB - 设置环境
- Node 和 MongoDB 示例
- Node 和 MongoDB - 连接数据库
- Node 和 MongoDB - 显示数据库
- Node 和 MongoDB - 删除数据库
- Node 和 MongoDB - 创建集合
- Node 和 MongoDB - 删除集合
- Node 和 MongoDB - 显示集合
- Node 和 MongoDB - 插入文档
- Node 和 MongoDB - 选中文档
- Node 和 MongoDB - 更新文档
- Node 和 MongoDB - 删除文档
- Node 和 MongoDB - 嵌入式文档
- Node 和 MongoDB - 限制记录
- Node 和 MongoDB - 排序记录
- Node 和 MongoDB 有用资源
- Node 和 MongoDB - 快速指南
- Node 和 MongoDB - 有用资源
- Node 和 MongoDB - 论坛
Node 和 MongoDB - 显示数据库
若要显示数据库,可以使用 admin.listDatabases() 方法获取所有数据库的名称,其中 admin 代表 admin 类。
MongoClient.connect(url, function(error, client) {
// Use the admin database for the operation
const adminDb = client.db('myDb').admin();
// List all the available databases
adminDb.listDatabases(function(err, dbs) {
console.log(dbs);
});
});
示例
尝试以下示例连接到 MongoDB 服务器 -
复制并粘贴以下示例,命名为 mongodb_example.js -
const MongoClient = require('mongodb').MongoClient;
// Prepare URL
const url = "mongodb://:27017/";
// make a connection to the database
MongoClient.connect(url, function(error, client) {
if (error) throw error;
console.log("Connected!");
// Use the admin database for the operation
const adminDb = client.db('myDb').admin();
// List all the available databases
adminDb.listDatabases(function(err, dbs) {
console.log(dbs);
});
// close the connection
client.close();
});
输出
使用 node 运行 mysql_example.js 脚本并验证输出。
node mongodb_example.js
Connected!
{
databases: [
{ name: 'admin', sizeOnDisk: 40960, empty: false },
{ name: 'config', sizeOnDisk: 36864, empty: false },
{ name: 'local', sizeOnDisk: 73728, empty: false }
],
totalSize: 151552,
ok: 1
}
广告