Skip to content

Commit 67d83bb

Browse files
DOCSP-9566 crud insert (#77)
* added CRUD Insert page
1 parent 431230f commit 67d83bb

File tree

2 files changed

+287
-3
lines changed

2 files changed

+287
-3
lines changed
Lines changed: 172 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,181 @@
11
=================
2-
Insert a Document
2+
Insert Operations
33
=================
44

55
.. default-domain:: mongodb
66

7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 1
11+
:class: singlecol
12+
713
Overview
814
--------
915

10-
In this section, we show you how to call the write operations to **insert**
11-
documents from a collection in your MongoDB database.
16+
In this guide, you will learn how to insert documents into MongoDB.
17+
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.
22+
23+
An insert operation inserts a single or multiple documents in MongoDB
24+
using the ``insertOne()``, ``insertMany()`` and ``bulkWrite()``
25+
methods.
26+
27+
The following sections focus on ``insertOne()`` and
28+
``insertMany()``. For information on how to use the ``bulkWrite()``
29+
method, see our ``Bulk Operations <TODO>`` page.
30+
31+
A Note About ``_id``
32+
--------------------
33+
34+
When inserting a document, MongoDB enforces one constraint on your
35+
documents by default. Each document *must* contain a unique ``_id``
36+
field.
37+
38+
There are two ways to manage this field:
39+
40+
- You can manage this field yourself, ensuring each value you use is unique.
41+
- You can let the driver automatically generate unique ObjectId values.
42+
43+
Unless you have provided strong guarantees for uniqueness, we recommend
44+
you let the driver automatically generate ``_id`` values.
45+
46+
.. note::
47+
48+
Duplicate ``_id`` values violate unique index constraints, resulting
49+
in a ``WriteError``.
50+
51+
For additional information on the classes and methods mentioned in this
52+
section, see the following resources:
53+
54+
- :manual:`Unique Indexes </core/index-unique/>`
55+
56+
Insert a Single Document
57+
------------------------
58+
59+
Use the ``insertOne()`` method when you want to insert a single
60+
document.
61+
62+
On successful insertion, the method returns an ``InsertOneResult``
63+
instance representing the ``_id`` of the new document.
64+
65+
Example
66+
~~~~~~~
67+
68+
The following example creates and inserts a document using the
69+
``insertOne()`` method:
70+
71+
.. literalinclude:: /includes/fundamentals/code-snippets/Insert.java
72+
:language: java
73+
:dedent:
74+
:start-after: begin insertOneExample
75+
:end-before: end insertOneExample
76+
77+
Your output should look something like this:
78+
79+
.. code-block:: json
80+
:copyable: false
81+
82+
Inserted a document with the following id: 60930c39a982931c20ef6cd6
83+
84+
For additional information on the classes and methods mentioned in this
85+
section, see the following resources:
86+
87+
- API Documentation on :java-sync-api:`insertOne() <com/mongodb/client/MongoCollection.html#insertOne(TDocument)>`
88+
- API Documentation on :java-docs:`InsertOneResult <apidocs/mongodb-driver-core/com/mongodb/client/result/InsertOneResult.html>`
89+
- Manual Explanation on :manual:`insertOne() </reference/method/db.collection.insertOne/>`
90+
- Runnable :doc:`Insert a Document Example </usage-examples/insertOne>`
91+
92+
Insert Multiple Documents
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+
103+
{ "_id": 3, "color": "red", "qty": 5 }
104+
{ "_id": 4, "color": "purple", "qty": 10 }
105+
{ "_id": 3, "color": "yellow", "qty": 3 }
106+
{ "_id": 6, "color": "blue", "qty": 8 }
107+
108+
If you attempt to insert these documents, a ``WriteError`` occurs at the
109+
third document and the documents prior to the error get inserted into
110+
your collection.
111+
112+
.. note::
113+
114+
Use a try-catch block to get an acknowledgment for successfully
115+
processed documents before the error occurs:
116+
117+
.. literalinclude:: /includes/fundamentals/code-snippets/Insert.java
118+
:language: java
119+
:dedent:
120+
:start-after: begin insertManyErrorExample
121+
:end-before: end insertManyErrorExample
122+
123+
The output consists of documents MongoDB can process and should look
124+
something like this:
125+
126+
.. code-block::
127+
:copyable: false
128+
129+
A MongoBulkWriteException occurred, but there are successfully processed
130+
documents with the following ids: [3, 4, 6]
131+
132+
If you look inside your collection, you see the following documents:
133+
134+
.. code-block:: json
135+
136+
{ "_id": 3, "color": "red", "qty": 5 }
137+
{ "_id": 4, "color": "purple", "qty": 10 }
138+
139+
On successful insertion, the method returns an ``InsertManyResult``
140+
instance representing the ``_id`` of each new document.
141+
142+
Example
143+
~~~~~~~
144+
145+
The following example creates and adds two documents to a ``List`` , and
146+
inserts the ``List`` using the ``insertMany()`` method:
147+
148+
.. literalinclude:: /includes/fundamentals/code-snippets/Insert.java
149+
:language: java
150+
:dedent:
151+
:start-after: begin insertManyExample
152+
:end-before: end insertManyExample
153+
154+
Your output should look something like this:
155+
156+
.. code-block::
157+
:copyable: false
158+
159+
Inserted documents with the following ids: [60930c3aa982931c20ef6cd7, 60930c3aa982931c20ef6cd8]
160+
161+
For additional information on the classes and methods mentioned in this
162+
section, see the following resources:
163+
164+
- :java-sync-api:`API Documentation on insertMany() <com/mongodb/client/MongoCollection.html#insertMany>`
165+
- :java-docs:`API Documentation on InsertManyResult <apidocs/mongodb-driver-core/com/mongodb/client/result/InsertManyResult.html>`
166+
- :manual:`Manual Explanation on insertMany() </reference/method/db.collection.insertMany/>`
167+
- :doc:`Runnable Insert Multiple Documents Example </usage-examples/insertMany>`
168+
169+
Summary
170+
-------
171+
172+
There are three ways to perform an insert operation, but we focused on two:
173+
174+
- The ``insertOne()`` method inserts a single document.
175+
- The ``insertMany()`` method inserts multiple documents.
176+
177+
Both methods automatically generate an ``_id`` if you omit the field in
178+
your document.
12179

180+
If the insertion is successful, both methods return an instance
181+
representing the ``_id`` of each new document.
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
package docs;
2+
3+
import com.mongodb.client.MongoClient;
4+
import com.mongodb.client.MongoClients;
5+
import com.mongodb.client.MongoCollection;
6+
import com.mongodb.client.MongoDatabase;
7+
import com.mongodb.client.result.InsertManyResult;
8+
import com.mongodb.client.result.InsertOneResult;
9+
10+
import com.mongodb.MongoBulkWriteException;
11+
12+
import org.bson.Document;
13+
import org.bson.types.ObjectId;
14+
15+
import java.util.List;
16+
import java.util.ArrayList;
17+
18+
public class Insert {
19+
20+
private final MongoCollection<Document> collection;
21+
private final MongoClient mongoClient;
22+
private final MongoDatabase database;
23+
24+
private Insert() {
25+
final String uri = System.getenv("DRIVER_REF_URI");
26+
27+
mongoClient = MongoClients.create(uri);
28+
database = mongoClient.getDatabase("crudOps");
29+
collection = database.getCollection("insert");
30+
}
31+
32+
public static void main(String[] args) {
33+
Insert insert = new Insert();
34+
35+
System.out.println("Insert One:");
36+
insert.insertOneExample();
37+
insert.preview();
38+
39+
System.out.println("Insert Many:");
40+
insert.insertManyExample();
41+
insert.preview();
42+
43+
System.out.println("Insert Many Error:");
44+
insert.insertManyErrorExample();
45+
insert.preview();
46+
}
47+
48+
private void insertOneExample() {
49+
collection.drop();
50+
// begin insertOneExample
51+
Document doc1 = new Document("color", "red").append("qty", 5);
52+
53+
InsertOneResult result = collection.insertOne(doc1);
54+
System.out.println("Inserted a document with the following id: "
55+
+ result.getInsertedId().asObjectId().getValue());
56+
// end insertOneExample
57+
}
58+
59+
private void insertManyExample() {
60+
collection.drop();
61+
// begin insertManyExample
62+
List<Document> documents = new ArrayList<>();
63+
64+
Document doc1 = new Document("color", "red").append("qty", 5);
65+
Document doc2 = new Document("color", "purple").append("qty", 10);
66+
67+
documents.add(doc1);
68+
documents.add(doc2);
69+
70+
InsertManyResult result = collection.insertMany(documents);
71+
72+
List<ObjectId> insertedIds = new ArrayList<>();
73+
result.getInsertedIds().values()
74+
.forEach(doc -> insertedIds.add(doc.asObjectId().getValue()));
75+
76+
System.out.println("Inserted documents with the following ids: " + insertedIds);
77+
78+
//end insertManyExample
79+
}
80+
81+
private void insertManyErrorExample() {
82+
collection.drop();
83+
84+
List<Document> documents = new ArrayList<>();
85+
86+
Document doc1 = new Document("_id", 3).append("color", "red").append("qty", 5);
87+
Document doc2 = new Document("_id", 4).append("color", "purple").append("qty", 10);
88+
Document doc3 = new Document("_id", 3).append("color", "yellow").append("qty", 3);
89+
Document doc4 = new Document("_id", 6).append("color", "blue").append("qty", 8);
90+
91+
documents.add(doc1);
92+
documents.add(doc2);
93+
documents.add(doc3);
94+
documents.add(doc4);
95+
96+
// begin insertManyErrorExample
97+
List<Integer> insertedIds = new ArrayList<>();
98+
try {
99+
InsertManyResult result = collection.insertMany(documents);
100+
result.getInsertedIds().values()
101+
.forEach(doc -> insertedIds.add(doc.asInt32().getValue()));
102+
System.out.println("Inserted documents with the following ids: " + insertedIds);
103+
} catch(MongoBulkWriteException exception) {
104+
exception.getWriteResult().getInserts()
105+
.forEach(doc -> insertedIds.add(doc.getId().asInt32().getValue()));
106+
System.out.println("A MongoBulkWriteException occurred, but there are " +
107+
"successfully processed documents with the following ids: " + insertedIds);
108+
}
109+
//end insertManyErrorExample
110+
}
111+
112+
private void preview(){
113+
collection.find().forEach(doc -> System.out.println(doc.toJson()));
114+
}
115+
}

0 commit comments

Comments
 (0)