I want to get database and collections names together as Object

Hi everyone, I have nexjs project where I use mongoClient to connect MongoDB, I want to take databases names and their collections names together as an object, I mean something like this, for example:
[
{database: “test”, collections: [“users”, “posts”, “jobs”]}
{database: “test1”, collections: [“users1”, “posts1”, “jobs1”]}
]

I get databases names and collections names but separately, and I can’t understand how can I push the database with the appropriate collections in an array.

Thanks for your attention!

this code is here, may you will understand better what I want to do

import clientPromise from "../../lib/mongo/mongo";

export default async function handler(req, res) {
  const client = await clientPromise;
  const db = client.db();

  switch (req.method) {
    case "GET":
      const dbNamesArray = await db.listCollections().toArray();

      const dbNames = await dbNamesArray.map((el) => {
        return el.name;
      });

      const dbAdmin = await db.admin().listDatabases({ nameOnly: true });
      const databases = await dbAdmin.databases;


      res.json({
        names: [{ database: db.databaseName, collection: dbNames }],
      });
      break;
  }
}

Hello @David_Takidze ,

Welcome to The MongoDB Community Forums! :wave:

I notice you haven’t had a response to this topic yet, were you able to solution?
If not, below is an example code giving out database and collections names similar to your requirements using javascript, you can integrate it with your code and test.

Sample code:

const { MongoClient } = require('mongodb');

const uri = 'mongodb+srv://<username>:<password>@<cluster>.mongodb.net/<database>?retryWrites=true&w=majority';
const client = new MongoClient(uri);

async function main() {
  try {
    await client.connect();

    const databases = await client.db().admin().listDatabases();
    const result = [];

    for (const database of databases.databases) {
      const collections = await client.db(database.name).listCollections().toArray();
      const collectionNames = collections.map(collection => collection.name);
      result.push({ database: database.name, collections: collectionNames });
    }

    console.log(result);

  } finally {
    await client.close();
  }
}

main().catch(console.error);

Output:

[
  {
    database: 'sample_analytics',
    collections: [ 'transactions', 'customers', 'accounts' ]
  },
  { database: 'sample_geospatial', collections: [ 'shipwrecks' ] },
  { database: 'sample_guides', collections: [ 'planets' ] },
  {
    database: 'sample_mflix',
    collections: [ 'comments', 'users', 'sessions', 'theaters', 'movies' ]
  }
]

Note: Please thoroughly test and verify to make sure it suits your use-case/requirements.

Regards,
Tarun

1 Like

Hello, first of all, sorry for the late reply, I saw your answer yesterday but I could not verify and use the code, thank’s for your answer, this solution works for me :fist: :heart:

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.