Learn how to set up and use DocumentDB with Node.js using the official MongoDB Node.js driver.
Before connecting from Node.js, make sure you have a running DocumentDB instance using Docker:
# Pull the latest DocumentDB Docker image
docker pull ghcr.io/documentdb/documentdb/documentdb-local:latest
# Tag the image for convenience
docker tag ghcr.io/documentdb/documentdb/documentdb-local:latest documentdb
# Run the container with your chosen username and password
docker run -dt -p 10260:10260 --name documentdb-container documentdb --username <YOUR_USERNAME> --password <YOUR_PASSWORD>
docker image rm -f ghcr.io/documentdb/documentdb/documentdb-local:latestNote: During the transition to the Linux Foundation, Docker images may still be hosted on Microsoft's container registry. These will be migrated to the new DocumentDB organization as the transition completes.
Note: Replace <YOUR_USERNAME> and <YOUR_PASSWORD> with your desired credentials. You must set these when creating the container for authentication to work.
Port Note: Port 10260 is used by default in these instructions to avoid conflicts with other local database services. You can use port 27017 (the standard MongoDB port) or any other available port if you prefer. If you do, be sure to update the port number in both your docker run command and your connection string accordingly.
Creating a new Node.js project
mkdir my-documentdb-app
cd my-documentdb-app
npm init -yInstalling the MongoDB driver
npm install mongodbconst { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
async function connect() {
try {
await client.connect();
const db = client.db('your_database');
return db;
} catch (error) {
console.error('Connection error:', error);
throw error;
}
}Creating collections
const collection = db.collection('your_collection');Document operations