我想将MongoDB的所有集合名称存储在变量/数组中。如何编写nodeJS代码来执行此操作?
答案 0 :(得分:1)
client.db(dbName);
创建db的客户端listCollections
方法以获取每个集合的详细信息。最终过滤并推送所需的信息并关闭连接。
const mongo = require('mongodb').MongoClient;
mongo.connect(connectionUrl, function(err, client) {
let allCollections = [];
//create client by providing database name
const db = client.db(dbName);
db.listCollections().toArray(function(err, collections) {
if(err) console.log(err);
//iterate to each collection detail and push just name in array
collections.forEach(eachCollectionDetails => {
allCollections.push(eachCollectionDetails.name);
});
//close client
client.close();
});
});