opusdev/vector-similarity-api
1
1# MongoDB Node.js Driver2 3The official [MongoDB](https://www.mongodb.com/) driver for Node.js.4 5**Upgrading to version 6? Take a look at our [upgrade guide here](https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/CHANGES_6.0.0.md)!**6 7## Quick Links8 9| Site | Link |10| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |11| Documentation | [www.mongodb.com/docs/drivers/node](https://www.mongodb.com/docs/drivers/node) |12| API Docs | [mongodb.github.io/node-mongodb-native](https://mongodb.github.io/node-mongodb-native) |13| `npm` package | [www.npmjs.com/package/mongodb](https://www.npmjs.com/package/mongodb) |14| MongoDB | [www.mongodb.com](https://www.mongodb.com) |15| MongoDB University | [learn.mongodb.com](https://learn.mongodb.com/catalog?labels=%5B%22Language%22%5D&values=%5B%22Node.js%22%5D) |16| MongoDB Developer Center | [www.mongodb.com/developer](https://www.mongodb.com/developer/languages/javascript/) |17| Stack Overflow | [stackoverflow.com](https://stackoverflow.com/search?q=%28%5Btypescript%5D+or+%5Bjavascript%5D+or+%5Bnode.js%5D%29+and+%5Bmongodb%5D) |18| Source Code | [github.com/mongodb/node-mongodb-native](https://github.com/mongodb/node-mongodb-native) |19| Upgrade to v6 | [etc/notes/CHANGES_6.0.0.md](https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/CHANGES_6.0.0.md) |20| Contributing | [CONTRIBUTING.md](https://github.com/mongodb/node-mongodb-native/blob/HEAD/CONTRIBUTING.md) |21| Changelog | [HISTORY.md](https://github.com/mongodb/node-mongodb-native/blob/HEAD/HISTORY.md) |22 23 24 25### Release Integrity26 27Releases are created automatically and signed using the [Node team's GPG key](https://pgp.mongodb.com/node-driver.asc). 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:28 29```shell30gpg --import node-driver.asc31```32 33The GitHub release contains a detached signature file for the NPM package (named34`mongodb-X.Y.Z.tgz.sig`).35 36The following command returns the link npm package.37```shell38npm view mongodb@vX.Y.Z dist.tarball39```40 41Using the result of the above command, a `curl` command can return the official npm package for the release.42 43To verify the integrity of the downloaded package, run the following command:44```shell45gpg --verify mongodb-X.Y.Z.tgz.sig mongodb-X.Y.Z.tgz46```47 48>[!Note]49No verification is done when using npm to install the package. The contents of the Github tarball and npm's tarball are identical.50 51The MongoDB Node.js driver follows [semantic versioning](https://semver.org/) for its releases.52 53### Bugs / Feature Requests54 55Think you’ve found a bug? Want to see a new feature in `node-mongodb-native`? Please open a56case in our issue management tool, JIRA:57 58- Create an account and login [jira.mongodb.org](https://jira.mongodb.org).59- Navigate to the NODE project [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE).60- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it.61 62Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the63Core Server (i.e. SERVER) project are **public**.64 65### Support / Feedback66 67For issues with, questions about, or feedback for the Node.js driver, please look into our [support channels](https://www.mongodb.com/docs/manual/support). Please do not email any of the driver developers directly with issues or questions - you're more likely to get an answer on the [MongoDB Community Forums](https://community.mongodb.com/tags/c/drivers-odms-connectors/7/node-js-driver).68 69### Change Log70 71Change history can be found in [`HISTORY.md`](https://github.com/mongodb/node-mongodb-native/blob/HEAD/HISTORY.md).72 73### Compatibility74 75The driver currently supports 4.2+ servers.76 77For exhaustive server and runtime version compatibility matrices, please refer to the following links:78 79- [MongoDB](https://www.mongodb.com/docs/drivers/node/current/compatibility/#mongodb-compatibility)80- [NodeJS](https://www.mongodb.com/docs/drivers/node/current/compatibility/#language-compatibility)81 82#### Component Support Matrix83 84The 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.85 86| Component | `mongodb@3.x` | `mongodb@4.x` | `mongodb@5.x` | `mongodb@<6.12` | `mongodb@>=6.12` |87| ------------------------------------------------------------------------------------ | ------------------ | ------------------ | ------------------ | --------------- | ------------------ |88| [bson](https://www.npmjs.com/package/bson) | ^1.0.0 | ^4.0.0 | ^5.0.0 | ^6.0.0 | ^6.0.0 |89| [bson-ext](https://www.npmjs.com/package/bson-ext) | ^1.0.0 \|\| ^2.0.0 | ^4.0.0 | N/A | N/A | N/A |90| [kerberos](https://www.npmjs.com/package/kerberos) | ^1.0.0 | ^1.0.0 \|\| ^2.0.0 | ^1.0.0 \|\| ^2.0.0 | ^2.0.1 | ^2.0.1 |91| [mongodb-client-encryption](https://www.npmjs.com/package/mongodb-client-encryption) | ^1.0.0 | ^1.0.0 \|\| ^2.0.0 | ^2.3.0 | ^6.0.0 | ^6.0.0 |92| [mongodb-legacy](https://www.npmjs.com/package/mongodb-legacy) | N/A | ^4.0.0 | ^5.0.0 | ^6.0.0 | ^6.0.0 |93| [@mongodb-js/zstd](https://www.npmjs.com/package/@mongodb-js/zstd) | N/A | ^1.0.0 | ^1.0.0 | ^1.1.0 | ^1.1.0 \|\| ^2.0.0 |94 95 96#### Typescript Version97 98We recommend using the latest version of typescript, however we currently ensure the driver's public types compile against `typescript@4.4.0`.99This is the lowest typescript version guaranteed to work with our driver: older versions may or may not work - use at your own risk.100Since typescript [does not restrict breaking changes to major versions](https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes), we consider this support best effort.101If you run into any unexpected compiler failures against our supported TypeScript versions, please let us know by filing an issue on our [JIRA](https://jira.mongodb.org/browse/NODE).102 103Additionally, our Typescript types are compatible with the ECMAScript standard for our minimum supported Node version. Currently, our Typescript targets es2021.104 105## Installation106 107The recommended way to get started using the Node.js 5.x driver is by using the `npm` (Node Package Manager) to install the dependency in your project.108 109After you've created your own project using `npm init`, you can run:110 111```bash112npm install mongodb113```114 115This will download the MongoDB driver and add a dependency entry in your `package.json` file.116 117If you are a Typescript user, you will need the Node.js type definitions to use the driver's definitions:118 119```sh120npm install -D @types/node121```122 123## Driver Extensions124 125The MongoDB driver can optionally be enhanced by the following feature packages:126 127Maintained by MongoDB:128 129- Zstd network compression - [@mongodb-js/zstd](https://github.com/mongodb-js/zstd)130- MongoDB field level and queryable encryption - [mongodb-client-encryption](https://github.com/mongodb/libmongocrypt#readme)131- GSSAPI / SSPI / Kerberos authentication - [kerberos](https://github.com/mongodb-js/kerberos)132 133Some of these packages include native C++ extensions.134Consult the [trouble shooting guide here](https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/native-extensions.md) if you run into compilation issues.135 136Third party:137 138- Snappy network compression - [snappy](https://github.com/Brooooooklyn/snappy)139- AWS authentication - [@aws-sdk/credential-providers](https://github.com/aws/aws-sdk-js-v3/tree/main/packages/credential-providers)140 141## Quick Start142 143This 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 [official documentation](https://www.mongodb.com/docs/drivers/node/).144 145### Create the `package.json` file146 147First, create a directory where your application will live.148 149```bash150mkdir myProject151cd myProject152```153 154Enter the following command and answer the questions to create the initial structure for your new project:155 156```bash157npm init -y158```159 160Next, install the driver as a dependency.161 162```bash163npm install mongodb164```165 166### Start a MongoDB Server167 168For complete MongoDB installation instructions, see [the manual](https://www.mongodb.com/docs/manual/installation/).169 1701. Download the right MongoDB version from [MongoDB](https://www.mongodb.org/downloads)1712. Create a database directory (in this case under **/data**).1723. Install and start a `mongod` process.173 174```bash175mongod --dbpath=/data176```177 178You should see the **mongod** process start up and print some status information.179 180### Connect to MongoDB181 182Create a new **app.js** file and add the following code to try out some basic CRUD183operations using the MongoDB driver.184 185Add code to connect to the server and the database **myProject**:186 187> **NOTE:** Resolving DNS Connection issues188>189> Node.js 18 changed the default DNS resolution ordering from always prioritizing IPv4 to the ordering190> returned by the DNS provider. In some environments, this can result in `localhost` resolving to191> an IPv6 address instead of IPv4 and a consequent failure to connect to the server.192>193> This can be resolved by:194>195> - specifying the IP address family using the MongoClient `family` option (`MongoClient(<uri>, { family: 4 } )`)196> - launching mongod or mongos with the ipv6 flag enabled ([--ipv6 mongod option documentation](https://www.mongodb.com/docs/manual/reference/program/mongod/#std-option-mongod.--ipv6))197> - using a host of `127.0.0.1` in place of localhost198> - specifying the DNS resolution ordering with the `--dns-resolution-order` Node.js command line argument (e.g. `node --dns-resolution-order=ipv4first`)199 200```js201const { MongoClient } = require('mongodb');202// or as an es module:203// import { MongoClient } from 'mongodb'204 205// Connection URL206const url = 'mongodb://localhost:27017';207const client = new MongoClient(url);208 209// Database Name210const dbName = 'myProject';211 212async function main() {213 // Use connect method to connect to the server214 await client.connect();215 console.log('Connected successfully to server');216 const db = client.db(dbName);217 const collection = db.collection('documents');218 219 // the following code examples can be pasted here...220 221 return 'done.';222}223 224main()225 .then(console.log)226 .catch(console.error)227 .finally(() => client.close());228```229 230Run your app from the command line with:231 232```bash233node app.js234```235 236The application should print **Connected successfully to server** to the console.237 238### Insert a Document239 240Add to **app.js** the following function which uses the **insertMany**241method to add three documents to the **documents** collection.242 243```js244const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }]);245console.log('Inserted documents =>', insertResult);246```247 248The **insertMany** command returns an object with information about the insert operations.249 250### Find All Documents251 252Add a query that returns all the documents.253 254```js255const findResult = await collection.find({}).toArray();256console.log('Found documents =>', findResult);257```258 259This query returns all the documents in the **documents** collection.260If you add this below the insertMany example, you'll see the documents you've inserted.261 262### Find Documents with a Query Filter263 264Add a query filter to find only documents which meet the query criteria.265 266```js267const filteredDocs = await collection.find({ a: 3 }).toArray();268console.log('Found documents filtered by { a: 3 } =>', filteredDocs);269```270 271Only the documents which match `'a' : 3` should be returned.272 273### Update a document274 275The following operation updates a document in the **documents** collection.276 277```js278const updateResult = await collection.updateOne({ a: 3 }, { $set: { b: 1 } });279console.log('Updated documents =>', updateResult);280```281 282The method updates the first document where the field **a** is equal to **3** by adding a new field **b** to the document set to **1**. `updateResult` contains information about whether there was a matching document to update or not.283 284### Remove a document285 286Remove the document where the field **a** is equal to **3**.287 288```js289const deleteResult = await collection.deleteMany({ a: 3 });290console.log('Deleted documents =>', deleteResult);291```292 293### Index a Collection294 295[Indexes](https://www.mongodb.com/docs/manual/indexes/) can improve your application's296performance. The following function creates an index on the **a** field in the297**documents** collection.298 299```js300const indexName = await collection.createIndex({ a: 1 });301console.log('index name =', indexName);302```303 304For more detailed information, see the [indexing strategies page](https://www.mongodb.com/docs/manual/applications/indexes/).305 306## Error Handling307 308If you need to filter certain errors from our driver, we have a helpful tree of errors described in [etc/notes/errors.md](https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/errors.md).309 310It is our recommendation to use `instanceof` checks on errors and to avoid relying on parsing `error.message` and `error.name` strings in your code.311We guarantee `instanceof` 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.312 313Any 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.314This means `instanceof` will always be able to accurately capture the errors that our driver throws.315 316```typescript317const client = new MongoClient(url);318await client.connect();319const collection = client.db().collection('collection');320 321try {322 await collection.insertOne({ _id: 1 });323 await collection.insertOne({ _id: 1 }); // duplicate key error324} catch (error) {325 if (error instanceof MongoServerError) {326 console.log(`Error worth logging: ${error}`); // special case for some reason327 }328 throw error; // still want to crash329}330```331 332## Nightly releases333 334If you need to test with a change from the latest `main` branch, our `mongodb` npm package has nightly versions released under the `nightly` tag.335 336```sh337npm install mongodb@nightly338```339 340Nightly versions are published regardless of testing outcome.341This means there could be semantic breakages or partially implemented features.342The nightly build is not suitable for production use.343 344## Next Steps345 346- [MongoDB Documentation](https://www.mongodb.com/docs/manual/)347- [MongoDB Node Driver Documentation](https://www.mongodb.com/docs/drivers/node/)348- [Read about Schemas](https://www.mongodb.com/docs/manual/core/data-modeling-introduction/)349- [Star us on GitHub](https://github.com/mongodb/node-mongodb-native)350 351## License352 353[Apache 2.0](LICENSE.md)354 355© 2012-present MongoDB [Contributors](https://github.com/mongodb/node-mongodb-native/blob/HEAD/CONTRIBUTORS.md) \356© 2009-2012 Christian Amor Kvalheim357 