@@ -7,82 +7,202 @@ Insert a Document
77.. contents:: On this page
88 :local:
99 :backlinks: none
10- :depth: 2
10+ :depth: 1
1111 :class: singlecol
1212
1313Overview
1414--------
1515
16- In this section, we show you how to call the write operations to **insert**
17- documents from a collection in your MongoDB database.
16+ In this guide, you can learn how to insert documents into MongoDB.
1817
19- Insert
20- ------
18+ You can use MongoDB to retrieve, update and delete information. To
19+ perform any of those operations, that information, such as user profiles
20+ and orders, needs to exist in MongoDB. For that information to exist,
21+ you need to first perform an **insert operation**.
2122
22- To add new documents to a collection, you can use
23- the ``insertOne()`` or the ``insertMany()`` methods. These methods accept
24- single or multiple documents, respectively. The driver automatically
25- generates a unique ``_id`` field for documents unless specified.
23+ An insert operation inserts a single or multiple documents in MongoDB
24+ using the ``insertOne()``, ``insertMany()`` and ``bulkWrite()`` methods.
2625
27- The following examples use a collection called ``pizzaCollection``,
28- which contains documents with the name and shape of a pizza.
26+ The following sections focus on ``insertOne()`` and ``insertMany()``. For an
27+ example on how to use the ``bulkWrite()`` method, see our runnable :doc:`Bulk
28+ Operations Example </usage-examples/bulkWrite>`.
2929
30- Insert a Document
31- ~~~~~~~~~~~~~~~~~
30+ A Note About ``_id``
31+ --------------------
3232
33- You can specify a document in a JSON object as follows:
33+ When inserting a document, MongoDB enforces one constraint on your
34+ documents by default. Each document *must* contain a unique ``_id``
35+ field.
3436
35- .. code-block:: javascript
37+ There are two ways to manage this field:
3638
37- const pizzaDocument = {
38- name: "Neapolitan pizza",
39- shape: "round"
40- };
39+ - You can manage this field yourself, ensuring each value you use is unique.
40+ - You can let the driver automatically generate unique ObjectId values.
4141
42- To insert this document into ``pizzaCollection``, pass ``pizzaDocument``
43- as the first parameter to the ``insertOne() `` method as shown below:
42+ Unless you have provided strong guarantees for uniqueness, we recommend
43+ you let the driver automatically generate ``_id `` values.
4444
45- .. code-block:: javascript
45+ .. note::
46+
47+ Duplicate ``_id`` values violate unique index constraints, resulting
48+ in a ``WriteError``.
49+
50+ For additional information about ``_id``, see the Server Manual Entry on
51+ :manual:`Unique Indexes </core/index-unique/>`.
52+
53+ Insert a Single Document
54+ ------------------------
4655
47- const result = await pizzaCollection.insertOne(pizzaDocument);
56+ Use the ``insertOne()`` method when you want to insert a single
57+ document.
4858
49- You can print the number of documents inserted by accessing the
50- ``insertedCount`` field of the operation result as follows:
59+ On successful insertion, the method returns an
60+ ``InsertOneResult`` instance representing the ``_id`` of
61+ the new document.
62+
63+ Example
64+ ~~~~~~~
65+
66+ The following example creates and inserts a document using the
67+ ``insertOne()`` method:
5168
5269.. code-block:: javascript
5370
54- console.dir(result.insertedCount); // should print 1 on successful insert
71+ const doc = { name: "Neapolitan pizza", shape: "round" };
72+ const result = await collection.insertOne(doc);
73+ console.log(
74+ `A document was inserted with the _id: ${result.insertedId}`,
75+ );
76+
77+ Your output should look something like this:
78+
79+ .. code-block::
80+ :copyable: false
81+
82+ A document was inserted with the _id: 60c79c0f4cc72b6bb31e3836
5583
56- For a runnable example, see the :doc:`insertOne() </usage-examples/insertOne>`
57- usage example.
84+ For additional information on the classes and methods mentioned in this
85+ section, see the following resources:
86+
87+ - API Documentation on :node-api-4.0:`insertOne() </classes/collection.html#insertone>`
88+ - API Documentation on :node-api-4.0:`InsertOneResult </interfaces/insertoneresult.html>`
89+ - Server Manual Entry on :manual:`insertOne() </reference/method/db.collection.insertOne/>`
90+ - Runnable :doc:`Insert a Document Example </usage-examples/insertOne>`
5891
5992Insert Multiple Documents
60- ~~~~~~~~~~~~~~~~~~~~~~~~~
93+ -------------------------
94+
95+ Use the ``insertMany()`` method when you want to insert multiple
96+ documents. This method inserts documents in the order specified until an
97+ exception occurs, if any.
98+
99+ For example, assume you want to insert the following documents:
100+
101+ .. code-block:: json
102+ :copyable: false
103+
104+ { "_id": 1, "color": "red" }
105+ { "_id": 2, "color": "purple" }
106+ { "_id": 1, "color": "yellow" }
107+ { "_id": 3, "color": "blue" }
108+
109+ If you attempt to insert these documents, a ``WriteError`` occurs at the
110+ third document and the documents prior to the error get inserted into
111+ your collection.
112+
113+ .. note::
114+
115+ Use a try-catch block to get an acknowledgment for successfully
116+ processed documents before the error occurs:
117+
118+ .. code-block:: javascript
119+
120+ try {
121+ const docs = [
122+ { "_id": 1, "color": "red"},
123+ { "_id": 2, "color": "purple"},
124+ { "_id": 1, "color": "yellow"},
125+ { "_id": 3, "color": "blue"}
126+ ];
127+
128+ const insertManyresult = await collection.insertMany(docs);
129+ let ids = insertManyresult.insertedIds;
130+
131+ console.log(`${insertManyresult.insertedCount} documents were inserted.`);
132+ for (let id of Object.values(ids)) {
133+ console.log(`Inserted a document with id ${id}`);
134+ }
135+ } catch(e) {
136+ console.log(`A MongoBulkWriteException occurred, but there are successfully processed documents.`);
137+ let ids = e.result.result.insertedIds;
138+ for (let id of Object.values(ids)) {
139+ console.log(`Processed a document with id ${id._id}`);
140+ }
141+ console.log(`Number of documents inserted: ${e.result.result.nInserted}`);
142+ }
143+
144+ The output consists of documents MongoDB can process and should look
145+ something like this:
146+
147+ .. code-block::
148+ :copyable: false
149+
150+ A MongoBulkWriteException occurred, but there are successfully processed documents.
151+ Processed a document with id 1
152+ Processed a document with id 2
153+ Processed a document with id 1
154+ Processed a document with id 3
155+ Number of documents inserted: 2
156+
157+ If you look inside your collection, you see the following documents:
158+
159+ .. code-block:: json
160+ :copyable: false
61161
62- You can specify multiple documents in an array of JSON objects as follows:
162+ { "_id": 1, "color": "red" }
163+ { "_id": 2, "color": "purple" }
63164
64- .. code-block:: javascript
165+ On successful insertion, the method returns an
166+ ``InsertManyResult`` instance representing the number of
167+ documents inserted and the ``_id`` of the new document.
65168
66- const pizzaDocuments = [
67- { name: "Sicilian pizza", shape: "square" },
68- { name: "New York pizza", shape: "round" },
69- { name: "Grandma pizza", shape: "square" }
70- ];
169+ Example
170+ ~~~~~~~
71171
72- To insert these documents into ``pizzaCollection``, pass
73- ``pizzaDocuments`` as the first parameter to the ``insertMany()`` method
74- as shown below:
172+ The following example creates and adds three documents using the
173+ ``insertMany()`` method:
75174
76175.. code-block:: javascript
77176
78- const result = await pizzaCollection.insertMany(pizzaDocuments);
177+ const docs = [
178+ { name: "Sicilian pizza", shape: "square" },
179+ { name: "New York pizza", shape: "round" },
180+ { name: "Grandma pizza", shape: "square" }
181+ ];
182+
183+ const insertManyresult = await collection.insertMany(docs);
184+ let ids = insertManyresult.insertedIds;
79185
80- You can print the number of documents inserted by accessing the
81- ``insertedCount`` field of the operation result as follows:
186+ console.log(`${insertManyresult.insertedCount} documents were inserted.`);
187+
188+ for (let id of Object.values(ids)) {
189+ console.log(`Inserted a document with id ${id}`);
190+ }
82191
83- .. code-block:: javascript
192+ Your output should look something like this:
193+
194+ .. code-block::
195+ :copyable: false
196+
197+ 3 documents were inserted.
198+ Inserted a document with id 60ca09f4a40cf1d1afcd93a2
199+ Inserted a document with id 60ca09f4a40cf1d1afcd93a3
200+ Inserted a document with id 60ca09f4a40cf1d1afcd93a4
84201
85- console.dir(result.insertedCount); // should print 3 on successful insert
202+ For additional information on the classes and methods mentioned in this
203+ section, see the following resources:
86204
87- For a runnable example, see the :doc:`insertMany() </usage-examples/insertMany>`
88- usage example.
205+ - API Documentation on :node-api-4.0:`insertMany() </classes/collection.html#insertmany>`
206+ - API Documentation on :node-api-4.0:`InsertManyResult </interfaces/insertmanyresult.html>`
207+ - Server Manual Entry on :manual:`insertMany() </reference/method/db.collection.insertMany/>`
208+ - Runnable :doc:`Insert Multiple Documents Example </usage-examples/insertMany>`
0 commit comments