You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

hace 4 años
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. # MongoDB NodeJS Driver
  2. [![npm](https://nodei.co/npm/mongodb.png?downloads=true&downloadRank=true)](https://nodei.co/npm/mongodb/)
  3. The official [MongoDB](https://www.mongodb.com/) driver for Node.js.
  4. **NOTE: v3.x released with breaking API changes. You can find a list of changes [here](CHANGES_3.0.0.md).**
  5. ## Version 4.0
  6. **Looking for the latest?** We're working on the next major version of the driver, now in beta.
  7. Check out our [beta version 4.0 here](https://github.com/mongodb/node-mongodb-native/tree/4.0), which includes a full migration of the driver to TypeScript.
  8. ## Quick Links
  9. | what | where |
  10. | ------------- | ---------------------------------------------------- |
  11. | documentation | http://mongodb.github.io/node-mongodb-native |
  12. | api-doc | http://mongodb.github.io/node-mongodb-native/3.6/api |
  13. | source | https://github.com/mongodb/node-mongodb-native |
  14. | mongodb | http://www.mongodb.org |
  15. ### Bugs / Feature Requests
  16. Think you’ve found a bug? Want to see a new feature in `node-mongodb-native`? Please open a
  17. case in our issue management tool, JIRA:
  18. - Create an account and login [jira.mongodb.org](https://jira.mongodb.org).
  19. - Navigate to the NODE project [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE).
  20. - Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it.
  21. Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the
  22. Core Server (i.e. SERVER) project are **public**.
  23. ### Support / Feedback
  24. For issues with, questions about, or feedback for the Node.js driver, please look into our [support channels](https://docs.mongodb.com/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).
  25. ### Change Log
  26. Change history can be found in [`HISTORY.md`](HISTORY.md).
  27. ### Compatibility
  28. For version compatibility matrices, please refer to the following links:
  29. - [MongoDB](https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-mongodb-node)
  30. - [NodeJS](https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-language-node)
  31. ## Installation
  32. The recommended way to get started using the Node.js driver is by using `npm` (Node Package Manager) to install the dependency in your project.
  33. ## MongoDB Driver
  34. 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.
  35. ```bash
  36. npm install mongodb --save
  37. ```
  38. This will download the MongoDB driver and add a dependency entry in your `package.json` file.
  39. You can also use the [Yarn](https://yarnpkg.com/en) package manager.
  40. ## Troubleshooting
  41. The MongoDB driver depends on several other packages. These are:
  42. - [bson](https://github.com/mongodb/js-bson)
  43. - [bson-ext](https://github.com/mongodb-js/bson-ext)
  44. - [kerberos](https://github.com/mongodb-js/kerberos)
  45. - [mongodb-client-encryption](https://github.com/mongodb/libmongocrypt#readme)
  46. 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.
  47. **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.**
  48. ### Diagnosing on UNIX
  49. 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.
  50. ```bash
  51. git clone https://github.com/mongodb-js/kerberos
  52. cd kerberos
  53. npm install
  54. ```
  55. 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:
  56. ```bash
  57. npm install -g node-gyp
  58. ```
  59. 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.
  60. ```bash
  61. cd yourproject
  62. npm install mongodb --save
  63. ```
  64. If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode.
  65. ```bash
  66. npm --loglevel verbose install mongodb
  67. ```
  68. This will print out all the steps npm is performing while trying to install the module.
  69. ### Diagnosing on Windows
  70. A compiler tool chain known to work for compiling `kerberos` on Windows is the following.
  71. - Visual Studio C++ 2010 (do not use higher versions)
  72. - Windows 7 64bit SDK
  73. - Python 2.7 or higher
  74. Open the Visual Studio command prompt. Ensure `node.exe` is in your path and install `node-gyp`.
  75. ```bash
  76. npm install -g node-gyp
  77. ```
  78. Next, you will have to build the project manually to test it. Clone the repo, install dependencies and rebuild:
  79. ```bash
  80. git clone https://github.com/christkv/kerberos.git
  81. cd kerberos
  82. npm install
  83. node-gyp rebuild
  84. ```
  85. This should rebuild the driver successfully if you have everything set up correctly.
  86. ### Other possible issues
  87. 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).
  88. Another tip is to ensure your user has write permission to wherever the Node.js modules are being installed.
  89. ## Quick Start
  90. 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](docs/reference/content/tutorials/main.md).
  91. ### Create the `package.json` file
  92. First, create a directory where your application will live.
  93. ```bash
  94. mkdir myproject
  95. cd myproject
  96. ```
  97. Enter the following command and answer the questions to create the initial structure for your new project:
  98. ```bash
  99. npm init
  100. ```
  101. Next, install the driver dependency.
  102. ```bash
  103. npm install mongodb --save
  104. ```
  105. 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.
  106. ### Start a MongoDB Server
  107. For complete MongoDB installation instructions, see [the manual](https://docs.mongodb.org/manual/installation/).
  108. 1. Download the right MongoDB version from [MongoDB](https://www.mongodb.org/downloads)
  109. 2. Create a database directory (in this case under **/data**).
  110. 3. Install and start a `mongod` process.
  111. ```bash
  112. mongod --dbpath=/data
  113. ```
  114. You should see the **mongod** process start up and print some status information.
  115. ### Connect to MongoDB
  116. Create a new **app.js** file and add the following code to try out some basic CRUD
  117. operations using the MongoDB driver.
  118. Add code to connect to the server and the database **myproject**:
  119. ```js
  120. const MongoClient = require('mongodb').MongoClient;
  121. const assert = require('assert');
  122. // Connection URL
  123. const url = 'mongodb://localhost:27017';
  124. // Database Name
  125. const dbName = 'myproject';
  126. const client = new MongoClient(url);
  127. // Use connect method to connect to the server
  128. client.connect(function(err) {
  129. assert.equal(null, err);
  130. console.log('Connected successfully to server');
  131. const db = client.db(dbName);
  132. client.close();
  133. });
  134. ```
  135. Run your app from the command line with:
  136. ```bash
  137. node app.js
  138. ```
  139. The application should print **Connected successfully to server** to the console.
  140. ### Insert a Document
  141. Add to **app.js** the following function which uses the **insertMany**
  142. method to add three documents to the **documents** collection.
  143. ```js
  144. const insertDocuments = function(db, callback) {
  145. // Get the documents collection
  146. const collection = db.collection('documents');
  147. // Insert some documents
  148. collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }], function(err, result) {
  149. assert.equal(err, null);
  150. assert.equal(3, result.result.n);
  151. assert.equal(3, result.ops.length);
  152. console.log('Inserted 3 documents into the collection');
  153. callback(result);
  154. });
  155. };
  156. ```
  157. The **insert** command returns an object with the following fields:
  158. - **result** Contains the result document from MongoDB
  159. - **ops** Contains the documents inserted with added **\_id** fields
  160. - **connection** Contains the connection used to perform the insert
  161. Add the following code to call the **insertDocuments** function:
  162. ```js
  163. const MongoClient = require('mongodb').MongoClient;
  164. const assert = require('assert');
  165. // Connection URL
  166. const url = 'mongodb://localhost:27017';
  167. // Database Name
  168. const dbName = 'myproject';
  169. // Use connect method to connect to the server
  170. MongoClient.connect(url, function(err, client) {
  171. assert.equal(null, err);
  172. console.log('Connected successfully to server');
  173. const db = client.db(dbName);
  174. insertDocuments(db, function() {
  175. client.close();
  176. });
  177. });
  178. ```
  179. Run the updated **app.js** file:
  180. ```bash
  181. node app.js
  182. ```
  183. The operation returns the following output:
  184. ```bash
  185. Connected successfully to server
  186. Inserted 3 documents into the collection
  187. ```
  188. ### Find All Documents
  189. Add a query that returns all the documents.
  190. ```js
  191. const findDocuments = function(db, callback) {
  192. // Get the documents collection
  193. const collection = db.collection('documents');
  194. // Find some documents
  195. collection.find({}).toArray(function(err, docs) {
  196. assert.equal(err, null);
  197. console.log('Found the following records');
  198. console.log(docs);
  199. callback(docs);
  200. });
  201. };
  202. ```
  203. This query returns all the documents in the **documents** collection. Add the **findDocument** method to the **MongoClient.connect** callback:
  204. ```js
  205. const MongoClient = require('mongodb').MongoClient;
  206. const assert = require('assert');
  207. // Connection URL
  208. const url = 'mongodb://localhost:27017';
  209. // Database Name
  210. const dbName = 'myproject';
  211. // Use connect method to connect to the server
  212. MongoClient.connect(url, function(err, client) {
  213. assert.equal(null, err);
  214. console.log('Connected correctly to server');
  215. const db = client.db(dbName);
  216. insertDocuments(db, function() {
  217. findDocuments(db, function() {
  218. client.close();
  219. });
  220. });
  221. });
  222. ```
  223. ### Find Documents with a Query Filter
  224. Add a query filter to find only documents which meet the query criteria.
  225. ```js
  226. const findDocuments = function(db, callback) {
  227. // Get the documents collection
  228. const collection = db.collection('documents');
  229. // Find some documents
  230. collection.find({ a: 3 }).toArray(function(err, docs) {
  231. assert.equal(err, null);
  232. console.log('Found the following records');
  233. console.log(docs);
  234. callback(docs);
  235. });
  236. };
  237. ```
  238. Only the documents which match `'a' : 3` should be returned.
  239. ### Update a document
  240. The following operation updates a document in the **documents** collection.
  241. ```js
  242. const updateDocument = function(db, callback) {
  243. // Get the documents collection
  244. const collection = db.collection('documents');
  245. // Update document where a is 2, set b equal to 1
  246. collection.updateOne({ a: 2 }, { $set: { b: 1 } }, function(err, result) {
  247. assert.equal(err, null);
  248. assert.equal(1, result.result.n);
  249. console.log('Updated the document with the field a equal to 2');
  250. callback(result);
  251. });
  252. };
  253. ```
  254. 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.
  255. ```js
  256. const MongoClient = require('mongodb').MongoClient;
  257. const assert = require('assert');
  258. // Connection URL
  259. const url = 'mongodb://localhost:27017';
  260. // Database Name
  261. const dbName = 'myproject';
  262. // Use connect method to connect to the server
  263. MongoClient.connect(url, function(err, client) {
  264. assert.equal(null, err);
  265. console.log('Connected successfully to server');
  266. const db = client.db(dbName);
  267. insertDocuments(db, function() {
  268. updateDocument(db, function() {
  269. client.close();
  270. });
  271. });
  272. });
  273. ```
  274. ### Remove a document
  275. Remove the document where the field **a** is equal to **3**.
  276. ```js
  277. const removeDocument = function(db, callback) {
  278. // Get the documents collection
  279. const collection = db.collection('documents');
  280. // Delete document where a is 3
  281. collection.deleteOne({ a: 3 }, function(err, result) {
  282. assert.equal(err, null);
  283. assert.equal(1, result.result.n);
  284. console.log('Removed the document with the field a equal to 3');
  285. callback(result);
  286. });
  287. };
  288. ```
  289. Add the new method to the **MongoClient.connect** callback function.
  290. ```js
  291. const MongoClient = require('mongodb').MongoClient;
  292. const assert = require('assert');
  293. // Connection URL
  294. const url = 'mongodb://localhost:27017';
  295. // Database Name
  296. const dbName = 'myproject';
  297. // Use connect method to connect to the server
  298. MongoClient.connect(url, function(err, client) {
  299. assert.equal(null, err);
  300. console.log('Connected successfully to server');
  301. const db = client.db(dbName);
  302. insertDocuments(db, function() {
  303. updateDocument(db, function() {
  304. removeDocument(db, function() {
  305. client.close();
  306. });
  307. });
  308. });
  309. });
  310. ```
  311. ### Index a Collection
  312. [Indexes](https://docs.mongodb.org/manual/indexes/) can improve your application's
  313. performance. The following function creates an index on the **a** field in the
  314. **documents** collection.
  315. ```js
  316. const indexCollection = function(db, callback) {
  317. db.collection('documents').createIndex({ a: 1 }, null, function(err, results) {
  318. console.log(results);
  319. callback();
  320. });
  321. };
  322. ```
  323. Add the `indexCollection` method to your app:
  324. ```js
  325. const MongoClient = require('mongodb').MongoClient;
  326. const assert = require('assert');
  327. // Connection URL
  328. const url = 'mongodb://localhost:27017';
  329. const dbName = 'myproject';
  330. // Use connect method to connect to the server
  331. MongoClient.connect(url, function(err, client) {
  332. assert.equal(null, err);
  333. console.log('Connected successfully to server');
  334. const db = client.db(dbName);
  335. insertDocuments(db, function() {
  336. indexCollection(db, function() {
  337. client.close();
  338. });
  339. });
  340. });
  341. ```
  342. For more detailed information, see the [tutorials](docs/reference/content/tutorials/main.md).
  343. ## Next Steps
  344. - [MongoDB Documentation](http://mongodb.org)
  345. - [Read about Schemas](http://learnmongodbthehardway.com)
  346. - [Star us on GitHub](https://github.com/mongodb/node-mongodb-native)
  347. ## License
  348. [Apache 2.0](LICENSE.md)
  349. © 2009-2012 Christian Amor Kvalheim
  350. © 2012-present MongoDB [Contributors](CONTRIBUTORS.md)