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://localhost: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