在 nodejs 脚本中列出 mongo 数据库中的所有集合

Listing all collections in a mongo database within a nodejs script

我在 shell 中找到了一些关于列出集合的答案,但我找到的关于在 nodejs 脚本中列出集合的所有答案似乎都已被弃用,答案如 collectionNamesmoongose.connection.db return 没有方法。

在 node.js 的 MongoDB 驱动程序的 2.0 版本中,您可以在光标上使用 listCollections to get a cursor that contains the information of all collections. You can then call toArray 来检索信息。

db.listCollections().toArray(function(err, collInfos) {
    // collInfos is an array of collection info objects that look like:
    // { name: 'test', options: {} }
});

如果您有权访问 async/await,在迭代器上承诺 toArray 并且不使用回调会更清晰。

static toArray(iterator) {
  return new Promise((resolve, reject) => {
    iterator.toArray((err, res) => {
      if (err) {
        reject(err);
      } else {
        resolve(res);
      }
    });
  });
}
const myArray = await toArray(db.listCollections());

这是一个完整的示例,说明如何使用 3.4 版本的 Mongo 节点驱动程序

const MongoClient = require("mongodb").MongoClient;

// Connection url
var url = 'mongodb://localhost:27017/test';
const client = new MongoClient(url, { useUnifiedTopology: true }); // { useUnifiedTopology: true } removes connection warnings;

const dbName = "test";

client
      .connect()
      .then(
        client =>
          client
            .db(dbName)
            .listCollections()
            .toArray() // Returns a promise that will resolve to the list of the collections
      )
      .then(cols => console.log("Collections", cols))
      .finally(() => client.close());
const collections = Object.keys(mongoose.connection.collections); 

这会为您提供 collections 的 JSON 文档。

   var resource=[]; 
   var ob=db.getSiblingDB('working_db');
   ob.getCollectionNames().forEach(function(doc){
        var regex = /^word|word1|word2|word3/i;
        var found = doc.match(regex);
        if(found){
            printjson(doc)
            resource.push({ resource: { db: "working_db", collection: doc }, actions: [ "insert","find","remove","update"] })
        }
    });

正则表达式用于获取我们需要列出的集合前缀名称中的特定特定单词,如果不需要,则将其删除。 这对于从大量集合列表中授予集合特定权限非常有用。

use admin,
db.createRole(
    {
      role: "ROLE_NAME",
      privileges: resource,
      roles: [
        {
          role: "clusterMonitor",
          db: "admin"
        }
      ]
    }
  )