list all collections in mongodb node js code example
Example 1: how to list all collections from a database in mongodb node js
var mongo = require('mongodb').MongoClient;
async function connect(){
const uri = "yourUri";
const client = new mongo(uri);
try {
await client.connect();
const db = client.db("testDatabase");
const collections = await db.collections();
collections.forEach (c=>console.log(c.collectionName));
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
connect().catch(console.error);
Example 2: list all collections in the MongoDB shell
JavaScript (shell):
db.getCollectionNames()
Node.js:
db.listCollections()
Example 3: show all collections in mongodb node js
async function connect(){
const uri = "yourUri";
const client = new mongo(uri);
try {
await client.connect();
const db = client.db("testDatabase");
const collections = await db.collections();
collections.forEach (c=>console.log(c.collectionName));
}
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
connect().catch(console.error);