简体   繁体   中英

How can I get all mongoDB collection names using Node.js code?

I want to store all collection names of MongoDB in a variable/array. How can I write nodeJS code to do that?

  1. create a connection by providing connection url.
  2. create a client to db using database name client.db(dbName);
  3. call listCollections method to get detail info of each collection.
  4. finally filter and push the required information and close the connection.

     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(); }); }); 
await db.listCollections().toArray().map(c => c.name);

这将返回一个包含每个集合名称的字符串数组。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM