Manage a MongoDB database using JavaScript

APPLIES TO: MongoDB

Your MongoDB server in Azure Cosmos DB is available from the common npm packages for MongoDB such as:

Note

The example code snippets are available on GitHub as a JavaScript project.

API for MongoDB reference documentation | MongoDB Package (npm)

Name a database

In Azure Cosmos DB, a database is analogous to a namespace. When you create a database, the database name forms a segment of the URI used to access the database resource and any child resources.

Here are some quick rules when naming a database:

  • Keep database names between 3 and 63 characters long
  • Database names can only contain lowercase letters, numbers, or the dash (-) character.
  • Database names must start with a lowercase letter or number.

Once created, the URI for a database is in this format:

https://<cosmos-account-name>.documents.azure.com/dbs/<database-name>

Get database instance

The database holds the collections and their documents. Use an instance of the Db class to access the databases on the server.

The following code snippets assume you've already created your client connection and that you close your client connection after these code snippets.

Get server information

Access the Admin class to retrieve server information. You don't need to specify the database name in the db method. The information returned is specific to MongoDB and doesn't represent the Azure Cosmos DB platform itself.

// Get server build info
const serverInfo = await client.db().admin().serverInfo();
console.log(`Server info:\n${Object.keys(serverInfo).map(key => `\t${key}: ${serverInfo[key]}\n`)}`);

// Get server status
const serverStatus = await client.db().admin().serverStatus();
console.log(`Server status:\n${Object.keys(serverStatus).map(key => `\t${key}: ${serverStatus[key]}\n`)}`);

// List all databases
const dbListResult = await client.db().admin().listDatabases();
console.log(`Databases:\n${dbListResult.databases.map(db => `\t${db.name}\n`)}`);

The preceding code snippet displays the following example console output:

Server info:
        version: 4.0.0
,       versionArray: 4,0,0,0
,       bits: 64
,       maxBsonObjectSize: 16777216
,       ok: 1

Server status:
        ok: 1

Databases:
        adventureworks
,       oldmain

done

Does database exist?

The native MongoDB driver for JavaScript creates the database if it doesn't exist when you access it. If you would prefer to know if the database already exists before using it, get the list of current databases and filter for the name:

// Get list of databases
const listResult = await client.db().admin().listDatabases();
if(listResult.databases.length === 0) {
  return 'No databases found';
}

// does database exist
const lookForDatabase = 'adventureworks';
const dbFound = listResult.databases.find(db => db.name===lookForDatabase).toArray();
if(dbFound) {
  return `Database exists:\t${lookForDatabase}`;
}

The preceding code snippet displays the following example console output:

Database exists:        adventureworks

Get list of databases, collections, and document count

When you manage your MongoDB server programmatically, it's helpful to know what databases and collections are on the server and how many documents in each collection.

// get list of databases
const listResult = await client.db().admin().listDatabases();
console.log("Databases:\n");

// loop through databases
for await (let database of listResult.databases) {

  console.log(`\t${database.name}\n`);

  // get database client
  const dbClient = client.db(database.name);

  // get collections in database
  const collections = await dbClient.listCollections();
  console.log("\n\t\tCollections:\n");

  // loop through collections
  for await (let collection of collections) {
    
    // get collection client
    const collectionClient = dbClient.collection(collection.name);

    // get doc count of collection
    const docCount = await collectionClient.countDocuments({});
    console.log(`\t\t\t${collection.name}: ${docCount} doc(s)\n`);
  }
}

The preceding code snippet displays the following example console output:

Databases:

        adventureworks


                Collections:

                        products: 1 doc(s)

        oldmain


                Collections:

                        central: 0 doc(s)

done

Get database object instance

To get a database object instance, call the following method. This method accepts an optional database name and can be part of a chain.

A database is created when it's accessed. The most common way to access a new database is to add a document to a collection. In one line of code using chained objects, the database, collection, and doc are created.

const insertOneResult = await client.db("adventureworks").collection("products").insertOne(doc);

Learn more about working with collections and documents.

Drop a database

A database is removed from the server using the dropDatabase method on the DB class.

// Drop a database, removing it permanently from the server.
const dropDatabase = await client.db("adventureworks").dropDatabase();
console.log(`Drop database:\t${JSON.stringify(dropDatabase)}`);

The preceding code snippet displays the following example console output:

Drop database:  true
done

See also