What is mongodb?
The mongodb npm package is the official Node.js driver for MongoDB. It provides a high-level API to connect to and interact with MongoDB databases. With this package, developers can perform CRUD operations, manage database connections, and work with MongoDB features like transactions, indexes, and aggregation.
What are mongodb's main functionalities?
Connecting to a MongoDB database
This code sample demonstrates how to connect to a MongoDB database using the MongoClient object provided by the mongodb package.
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
async function connect() {
try {
await client.connect();
console.log('Connected to MongoDB');
} catch (e) {
console.error(e);
}
}
connect();
CRUD Operations
This code sample shows how to perform CRUD (Create, Read, Update, Delete) operations on a MongoDB collection using the mongodb package.
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
const dbName = 'myDatabase';
async function crudOperations() {
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('documents');
// Create a document
await collection.insertOne({ a: 1 });
// Read documents
const docs = await collection.find({}).toArray();
// Update a document
await collection.updateOne({ a: 1 }, { $set: { b: 1 } });
// Delete a document
await collection.deleteOne({ b: 1 });
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
crudOperations();
Index Management
This code sample illustrates how to manage indexes in a MongoDB collection, including creating an index and listing all indexes.
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
const dbName = 'myDatabase';
async function manageIndexes() {
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('documents');
// Create an index
await collection.createIndex({ a: 1 });
// List indexes
const indexes = await collection.indexes();
console.log(indexes);
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
manageIndexes();
Aggregation
This code sample demonstrates how to use the aggregation framework provided by MongoDB to process data and compute aggregated results.
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
const dbName = 'myDatabase';
async function aggregateData() {
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('documents');
// Perform an aggregation query
const aggregation = await collection.aggregate([
{ $match: { a: 1 } },
{ $group: { _id: '$b', total: { $sum: 1 } } }
]).toArray();
console.log(aggregation);
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
aggregateData();
Other packages similar to mongodb
mongoose
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB. Mongoose offers a more structured approach to data handling with predefined schemas compared to the flexibility of the mongodb package.
couchbase
Couchbase is the official Node.js client library for the Couchbase database. While Couchbase is a different NoSQL database system with its own set of features and capabilities, the couchbase npm package offers similar functionalities in terms of CRUD operations, connection management, and querying as the mongodb package does for MongoDB.
redis
Redis is an in-memory data structure store, used as a database, cache, and message broker. The npm package for Redis provides Node.js bindings to the Redis server. It is similar to mongodb in that it allows for data storage and retrieval, but it operates in-memory and is typically used for different use cases such as caching.


Description
The official MongoDB driver for Node.js. Provides a high-level API on top of mongodb-core that is meant for end users.
NOTE: v3.x was recently released with breaking API changes. You can find a list of changes here.
MongoDB Node.JS Driver
Bugs / Feature Requests
Think you’ve found a bug? Want to see a new feature in node-mongodb-native
? Please open a
case in our issue management tool, JIRA:
Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the
Core Server (i.e. SERVER) project are public.
Questions and Bug Reports
Change Log
Change history can be found in HISTORY.md
.
Installation
The recommended way to get started using the Node.js 3.0 driver is by using the npm
(Node Package Manager) to install the dependency in your project.
MongoDB Driver
Given that you have created your own project using npm init
we install the MongoDB driver and its dependencies by executing the following npm
command.
npm install mongodb --save
This will download the MongoDB driver and add a dependency entry in your package.json
file.
You can also use the Yarn package manager.
Troubleshooting
The MongoDB driver depends on several other packages. These are:
The kerberos
package is a C++ extension that requires a build environment to be installed on your system. You must be able to build Node.js itself in order to compile and install the kerberos
module. Furthermore, the kerberos
module requires the MIT Kerberos package to correctly compile on UNIX operating systems. Consult your UNIX operation system package manager for what libraries to install.
Windows already contains the SSPI API used for Kerberos authentication. However, you will need to install a full compiler tool chain using Visual Studio C++ to correctly install the Kerberos extension.
Diagnosing on UNIX
If you don’t have the build-essentials, this module won’t build. In the case of Linux, you will need gcc, g++, Node.js with all the headers and Python. The easiest way to figure out what’s missing is by trying to build the Kerberos project. You can do this by performing the following steps.
git clone https://github.com/mongodb-js/kerberos
cd kerberos
npm install
If all the steps complete, you have the right toolchain installed. If you get the error "node-gyp not found," you need to install node-gyp
globally:
npm install -g node-gyp
If it correctly compiles and runs the tests you are golden. We can now try to install the mongod
driver by performing the following command.
cd yourproject
npm install mongodb --save
If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode.
npm --loglevel verbose install mongodb
This will print out all the steps npm is performing while trying to install the module.
Diagnosing on Windows
A compiler tool chain known to work for compiling kerberos
on Windows is the following.
- Visual Studio C++ 2010 (do not use higher versions)
- Windows 7 64bit SDK
- Python 2.7 or higher
Open the Visual Studio command prompt. Ensure node.exe
is in your path and install node-gyp
.
npm install -g node-gyp
Next, you will have to build the project manually to test it. Clone the repo, install dependencies and rebuild:
git clone https://github.com/christkv/kerberos.git
cd kerberos
npm install
node-gyp rebuild
This should rebuild the driver successfully if you have everything set up correctly.
Other possible issues
Your Python installation might be hosed making gyp break. Test your deployment environment first by trying to build Node.js itself on the server in question, as this should unearth any issues with broken packages (and there are a lot of broken packages out there).
Another tip is to ensure your user has write permission to wherever the Node.js modules are being installed.
Quick Start
This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the tutorials.
Create the package.json
file
First, create a directory where your application will live.
mkdir myproject
cd myproject
Enter the following command and answer the questions to create the initial structure for your new project:
npm init
Next, install the driver dependency.
npm install mongodb --save
You should see NPM download a lot of files. Once it's done you'll find all the downloaded packages under the node_modules directory.
Start a MongoDB Server
For complete MongoDB installation instructions, see the manual.
- Download the right MongoDB version from MongoDB
- Create a database directory (in this case under /data).
- Install and start a
mongod
process.
mongod --dbpath=/data
You should see the mongod process start up and print some status information.
Connect to MongoDB
Create a new app.js file and add the following code to try out some basic CRUD
operations using the MongoDB driver.
Add code to connect to the server and the database myproject:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
const dbName = 'myproject';
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
Run your app from the command line with:
node app.js
The application should print Connected successfully to server to the console.
Insert a Document
Add to app.js the following function which uses the insertMany
method to add three documents to the documents collection.
const insertDocuments = function(db, callback) {
const collection = db.collection('documents');
collection.insertMany([
{a : 1}, {a : 2}, {a : 3}
], function(err, result) {
assert.equal(err, null);
assert.equal(3, result.result.n);
assert.equal(3, result.ops.length);
console.log("Inserted 3 documents into the collection");
callback(result);
});
}
The insert command returns an object with the following fields:
- result Contains the result document from MongoDB
- ops Contains the documents inserted with added _id fields
- connection Contains the connection used to perform the insert
Add the following code to call the insertDocuments function:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
const dbName = 'myproject';
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
insertDocuments(db, function() {
client.close();
});
});
Run the updated app.js file:
node app.js
The operation returns the following output:
Connected successfully to server
Inserted 3 documents into the collection
Find All Documents
Add a query that returns all the documents.
const findDocuments = function(db, callback) {
const collection = db.collection('documents');
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
console.log(docs)
callback(docs);
});
}
This query returns all the documents in the documents collection. Add the findDocument method to the MongoClient.connect callback:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
const dbName = 'myproject';
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected correctly to server");
const db = client.db(dbName);
insertDocuments(db, function() {
findDocuments(db, function() {
client.close();
});
});
});
Find Documents with a Query Filter
Add a query filter to find only documents which meet the query criteria.
const findDocuments = function(db, callback) {
const collection = db.collection('documents');
collection.find({'a': 3}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
console.log(docs);
callback(docs);
});
}
Only the documents which match 'a' : 3
should be returned.
Update a document
The following operation updates a document in the documents collection.
const updateDocument = function(db, callback) {
const collection = db.collection('documents');
collection.updateOne({ a : 2 }
, { $set: { b : 1 } }, function(err, result) {
assert.equal(err, null);
assert.equal(1, result.result.n);
console.log("Updated the document with the field a equal to 2");
callback(result);
});
}
The method updates the first document where the field a is equal to 2 by adding a new field b to the document set to 1. Next, update the callback function from MongoClient.connect to include the update method.
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
const dbName = 'myproject';
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
insertDocuments(db, function() {
updateDocument(db, function() {
client.close();
});
});
});
Remove a document
Remove the document where the field a is equal to 3.
const removeDocument = function(db, callback) {
const collection = db.collection('documents');
collection.deleteOne({ a : 3 }, function(err, result) {
assert.equal(err, null);
assert.equal(1, result.result.n);
console.log("Removed the document with the field a equal to 3");
callback(result);
});
}
Add the new method to the MongoClient.connect callback function.
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
const dbName = 'myproject';
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
insertDocuments(db, function() {
updateDocument(db, function() {
removeDocument(db, function() {
client.close();
});
});
});
});
Index a Collection
Indexes can improve your application's
performance. The following function creates an index on the a field in the
documents collection.
const indexCollection = function(db, callback) {
db.collection('documents').createIndex(
{ "a": 1 },
null,
function(err, results) {
console.log(results);
callback();
}
);
};
Add the indexCollection
method to your app:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
const dbName = 'myproject';
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
insertDocuments(db, function() {
indexCollection(db, function() {
client.close();
});
});
});
For more detailed information, see the tutorials.
Next Steps