Node & MongoDB - 显示集合
要显示数据库的集合,可以使用 database.listCollections() 方法获取集合列表。
MongoClient.connect(url, function(error, client) {
// 连接数据库
const database = client.db('myDb');
// 获取集合列表
database.listCollections().toArray(function(err, collections) {
collections.forEach(collection => console.log(collection.name));
});
});
示例
尝试以下示例创建 mongodb 集合 −
复制并粘贴以下示例为 mongodb_example.js −
const MongoClient = require('mongodb').MongoClient;
// 准备 URL
const url = "mongodb://localhost:27017/";
// 建立与数据库的连接
MongoClient.connect(url, function(error, client) {
if (error) throw error;
console.log("Connected!");
// 连接数据库
const database = client.db('myDb');
// Create the collection
database.createCollection('sampleCollection');
database.listCollections().toArray(function(err, collections) {
collections.forEach(collection => console.log(collection.name));
});
// 关闭连接
client.close();
});
输出
使用 Node 执行 mysql_example.js 脚本并验证输出。
node mongodb_example.js Connected! sampleCollection

