ToollessToolless

Database

Database-level operations

Getting a Database

const db = client.db("myapp");

Methods

collection(name)

Get a collection:

const users = db.collection("users");

listCollections()

List all collections in the database:

const collections = await db.listCollections();
// ['users', 'posts', 'comments']

dropCollection(name)

Drop a collection:

await db.dropCollection("temp");

stats()

Get database statistics:

const stats = await db.stats();
// {
//   collections: 3,
//   documents: 1500,
//   size: 2457600
// }

Example

const db = client.db("myapp");

const collections = await db.listCollections();
console.log("Collections:", collections);

for (const name of collections) {
  const coll = db.collection(name);
  const count = await coll.countDocuments({});
  console.log(`${name}: ${count} documents`);
}

On this page