- Notifications
You must be signed in to change notification settings - Fork1.8k
The official MongoDB Node.js driver
License
mongodb/node-mongodb-native
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
The officialMongoDB driver for Node.js.
Upgrading to version 6? Take a look at ourupgrade guide here!
Site | Link |
---|---|
Documentation | www.mongodb.com/docs/drivers/node |
API Docs | mongodb.github.io/node-mongodb-native |
npm package | www.npmjs.com/package/mongodb |
MongoDB | www.mongodb.com |
MongoDB University | learn.mongodb.com |
MongoDB Developer Center | www.mongodb.com/developer |
Stack Overflow | stackoverflow.com |
Source Code | github.com/mongodb/node-mongodb-native |
Upgrade to v6 | etc/notes/CHANGES_6.0.0.md |
Contributing | CONTRIBUTING.md |
Changelog | HISTORY.md |
Releases are created automatically and signed using theNode team's GPG key. This applies to the git tag as well as all release packages provided as part of a GitHub release. To verify the provided packages, download the key and import it using gpg:
gpg --import node-driver.asc
The GitHub release contains a detached signature file for the NPM package (namedmongodb-X.Y.Z.tgz.sig
).
The following command returns the link npm package.
npm view mongodb@vX.Y.Z dist.tarball
Using the result of the above command, acurl
command can return the official npm package for the release.
To verify the integrity of the downloaded package, run the following command:
gpg --verify mongodb-X.Y.Z.tgz.sig mongodb-X.Y.Z.tgz
Note
No verification is done when using npm to install the package. The contents of the Github tarball and npm's tarball are identical.
The MongoDB Node.js driver followssemantic versioning for its releases.
Think you’ve found a bug? Want to see a new feature innode-mongodb-native
? Please open acase in our issue management tool, JIRA:
- Create an account and loginjira.mongodb.org.
- Navigate to the NODE projectjira.mongodb.org/browse/NODE.
- ClickCreate Issue - Please provide as much information as possible about the issue type and how to reproduce it.
Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and theCore Server (i.e. SERVER) project arepublic.
For issues with, questions about, or feedback for the Node.js driver, please look into oursupport channels. Please do not email any of the driver developers directly with issues or questions - you're more likely to get an answer on theMongoDB Community Forums.
Change history can be found inHISTORY.md
.
The driver currently supports 4.2+ servers.
For exhaustive server and runtime version compatibility matrices, please refer to the following links:
The following table describes add-on component version compatibility for the Node.js driver. Only packages with versions in these supported ranges are stable when used in combination.
Component | mongodb@3.x | mongodb@4.x | mongodb@5.x | mongodb@<6.12 | mongodb@>=6.12 |
---|---|---|---|---|---|
bson | ^1.0.0 | ^4.0.0 | ^5.0.0 | ^6.0.0 | ^6.0.0 |
bson-ext | ^1.0.0 || ^2.0.0 | ^4.0.0 | N/A | N/A | N/A |
kerberos | ^1.0.0 | ^1.0.0 || ^2.0.0 | ^1.0.0 || ^2.0.0 | ^2.0.1 | ^2.0.1 |
mongodb-client-encryption | ^1.0.0 | ^1.0.0 || ^2.0.0 | ^2.3.0 | ^6.0.0 | ^6.0.0 |
mongodb-legacy | N/A | ^4.0.0 | ^5.0.0 | ^6.0.0 | ^6.0.0 |
@mongodb-js/zstd | N/A | ^1.0.0 | ^1.0.0 | ^1.1.0 | ^1.1.0 || ^2.0.0 |
We recommend using the latest version of typescript, however we currently ensure the driver's public types compile againsttypescript@4.4.0
.This is the lowest typescript version guaranteed to work with our driver: older versions may or may not work - use at your own risk.Since typescriptdoes not restrict breaking changes to major versions, we consider this support best effort.If you run into any unexpected compiler failures against our supported TypeScript versions, please let us know by filing an issue on ourJIRA.
Additionally, our Typescript types are compatible with the ECMAScript standard for our minimum supported Node version. Currently, our Typescript targets es2021.
The recommended way to get started using the Node.js 5.x driver is by using thenpm
(Node Package Manager) to install the dependency in your project.
After you've created your own project usingnpm init
, you can run:
npm install mongodb
This will download the MongoDB driver and add a dependency entry in yourpackage.json
file.
If you are a Typescript user, you will need the Node.js type definitions to use the driver's definitions:
npm install -D @types/node
The MongoDB driver can optionally be enhanced by the following feature packages:
Maintained by MongoDB:
- Zstd network compression -@mongodb-js/zstd
- MongoDB field level and queryable encryption -mongodb-client-encryption
- GSSAPI / SSPI / Kerberos authentication -kerberos
Some of these packages include native C++ extensions.Consult thetrouble shooting guide here if you run into compilation issues.
Third party:
- Snappy network compression -snappy
- AWS authentication -@aws-sdk/credential-providers
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 theofficial documentation.
First, create a directory where your application will live.
mkdir myProjectcd myProject
Enter the following command and answer the questions to create the initial structure for your new project:
npm init -y
Next, install the driver as a dependency.
npm install mongodb
For complete MongoDB installation instructions, seethe manual.
- Download the right MongoDB version fromMongoDB
- Create a database directory (in this case under/data).
- Install and start a
mongod
process.
mongod --dbpath=/data
You should see themongod process start up and print some status information.
Create a newapp.js file and add the following code to try out some basic CRUDoperations using the MongoDB driver.
Add code to connect to the server and the databasemyProject:
NOTE: Resolving DNS Connection issues
Node.js 18 changed the default DNS resolution ordering from always prioritizing IPv4 to the orderingreturned by the DNS provider. In some environments, this can result in
localhost
resolving toan IPv6 address instead of IPv4 and a consequent failure to connect to the server.This can be resolved by:
- specifying the IP address family using the MongoClient
family
option (MongoClient(<uri>, { family: 4 } )
)- launching mongod or mongos with the ipv6 flag enabled (--ipv6 mongod option documentation)
- using a host of
127.0.0.1
in place of localhost- specifying the DNS resolution ordering with the
--dns-resolution-order
Node.js command line argument (e.g.node --dns-resolution-order=ipv4first
)
const{ MongoClient}=require('mongodb');// or as an es module:// import { MongoClient } from 'mongodb'// Connection URLconsturl='mongodb://localhost:27017';constclient=newMongoClient(url);// Database NameconstdbName='myProject';asyncfunctionmain(){// Use connect method to connect to the serverawaitclient.connect();console.log('Connected successfully to server');constdb=client.db(dbName);constcollection=db.collection('documents');// the following code examples can be pasted here...return'done.';}main().then(console.log).catch(console.error).finally(()=>client.close());
Run your app from the command line with:
node app.js
The application should printConnected successfully to server to the console.
Add toapp.js the following function which uses theinsertManymethod to add three documents to thedocuments collection.
constinsertResult=awaitcollection.insertMany([{a:1},{a:2},{a:3}]);console.log('Inserted documents =>',insertResult);
TheinsertMany command returns an object with information about the insert operations.
Add a query that returns all the documents.
constfindResult=awaitcollection.find({}).toArray();console.log('Found documents =>',findResult);
This query returns all the documents in thedocuments collection.If you add this below the insertMany example, you'll see the documents you've inserted.
Add a query filter to find only documents which meet the query criteria.
constfilteredDocs=awaitcollection.find({a:3}).toArray();console.log('Found documents filtered by { a: 3 } =>',filteredDocs);
Only the documents which match'a' : 3
should be returned.
The following operation updates a document in thedocuments collection.
constupdateResult=awaitcollection.updateOne({a:3},{$set:{b:1}});console.log('Updated documents =>',updateResult);
The method updates the first document where the fielda is equal to3 by adding a new fieldb to the document set to1.updateResult
contains information about whether there was a matching document to update or not.
Remove the document where the fielda is equal to3.
constdeleteResult=awaitcollection.deleteMany({a:3});console.log('Deleted documents =>',deleteResult);
Indexes can improve your application'sperformance. The following function creates an index on thea field in thedocuments collection.
constindexName=awaitcollection.createIndex({a:1});console.log('index name =',indexName);
For more detailed information, see theindexing strategies page.
If you need to filter certain errors from our driver, we have a helpful tree of errors described inetc/notes/errors.md.
It is our recommendation to useinstanceof
checks on errors and to avoid relying on parsingerror.message
anderror.name
strings in your code.We guaranteeinstanceof
checks will pass according to semver guidelines, but errors may be sub-classed or their messages may change at any time, even patch releases, as we see fit to increase the helpfulness of the errors.
Any new errors we add to the driver will directly extend an existing error class and no existing error will be moved to a different parent class outside of a major release.This meansinstanceof
will always be able to accurately capture the errors that our driver throws.
constclient=newMongoClient(url);awaitclient.connect();constcollection=client.db().collection('collection');try{awaitcollection.insertOne({_id:1});awaitcollection.insertOne({_id:1});// duplicate key error}catch(error){if(errorinstanceofMongoServerError){console.log(`Error worth logging:${error}`);// special case for some reason}throwerror;// still want to crash}
If you need to test with a change from the latestmain
branch, ourmongodb
npm package has nightly versions released under thenightly
tag.
npm install mongodb@nightly
Nightly versions are published regardless of testing outcome.This means there could be semantic breakages or partially implemented features.The nightly build is not suitable for production use.
© 2012-present MongoDBContributors
© 2009-2012 Christian Amor Kvalheim
About
The official MongoDB Node.js driver
Topics
Resources
License
Code of conduct
Uh oh!
There was an error while loading.Please reload this page.