- 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 - 显示集合
要显示数据库的集合,可以使用 **database.listCollections()** 方法来获取集合列表。
MongoClient.connect(url, function(error, client) {
// Connect to the database
const database = client.db('myDb');
// get the list of collections
database.listCollections().toArray(function(err, collections) {
collections.forEach(collection => console.log(collection.name));
});
});
示例
尝试以下示例来创建一个 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!");
// Connect to the database
const database = client.db('myDb');
// Create the collection
database.createCollection('sampleCollection');
database.listCollections().toArray(function(err, collections) {
collections.forEach(collection => console.log(collection.name));
});
// close the connection
client.close();
});
输出
使用 node 执行 mysql_example.js 脚本并验证输出。
node mongodb_example.js Connected! sampleCollection
广告