Skip to content

Commit 5e0d358

Browse files
DOCSP-15337 crud update (#73)
* added Change A Document page
1 parent 852dad0 commit 5e0d358

File tree

3 files changed

+272
-2
lines changed

3 files changed

+272
-2
lines changed

source/fundamentals/crud/write-operations.txt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,19 @@ Write Operations
66

77
- :doc:`/fundamentals/crud/write-operations/insert`
88
- :doc:`/fundamentals/crud/write-operations/delete`
9+
- :doc:`/fundamentals/crud/write-operations/change-a-document`
910
- :doc:`/fundamentals/crud/write-operations/upsert`
1011

1112
..
12-
- :doc:`/fundamentals/crud/write-operations/change-a-document`
1313
- :doc:`/fundamentals/crud/write-operations/embedded-arrays`
1414

1515
.. toctree::
1616
:caption: Write Operations
1717

1818
/fundamentals/crud/write-operations/insert
1919
/fundamentals/crud/write-operations/delete
20+
/fundamentals/crud/write-operations/change-a-document
2021
/fundamentals/crud/write-operations/upsert
2122

2223
..
23-
/fundamentals/crud/write-operations/change-a-document
2424
/fundamentals/crud/write-operations/embedded-arrays
Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
=================
2+
Change a Document
3+
=================
4+
5+
.. default-domain:: mongodb
6+
7+
In this page, you can learn how to change documents in a MongoDB collection
8+
using two distinct operation types:
9+
10+
- :ref:`Update <update-operation>`
11+
- :ref:`Replace <replace-operation>`
12+
13+
Update operations specify the fields and values to change in one or more
14+
documents. A replace operation specifies the fields and values to replace
15+
a single document from your collection.
16+
17+
In the following examples, a paint store sells five different
18+
colors of paint. The ``paint_inventory`` collection represents their
19+
current inventory:
20+
21+
.. code-block:: json
22+
23+
{ "_id": 1, "color": "red", "qty": 5 }
24+
{ "_id": 2, "color": "purple", "qty": 8 }
25+
{ "_id": 3, "color": "yellow", "qty": 0 }
26+
{ "_id": 4, "color": "green", "qty": 6 }
27+
{ "_id": 5, "color": "pink", "qty": 0 }
28+
29+
.. _update-operation:
30+
31+
Update
32+
------
33+
34+
Update operations can change the fields and values. They apply changes
35+
specified in an update document to one or more documents that match your
36+
query filter.
37+
38+
The :java-docs:`updateOne() <apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#updateOne(org.bson.conversions.Bson,org.bson.conversions.Bson)>`
39+
method changes the first document your query filter matches and the
40+
:java-docs:`updateMany() <apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#updateMany(org.bson.conversions.Bson,org.bson.conversions.Bson)>`
41+
method changes all the documents your query filter matches.
42+
43+
You can call the ``updateOne()`` and ``updateMany()`` methods on a
44+
``MongoCollection`` instance as follows:
45+
46+
.. code-block:: java
47+
48+
collection.updateOne(query, updateDocument);
49+
50+
collection.updateMany(query, updateDocument);
51+
52+
Update Operation Parameters:
53+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
54+
55+
- ``query`` specifies a query filter with the criteria to match documents to update in your collection
56+
- ``updateDocument`` specifies the fields and values to change in the matching document or documents. For this example, we use the :doc:`Updates builder </fundamentals/builders/updates>` to create the update document.
57+
58+
You can create the ``updateDocument`` using an ``Updates`` builder as
59+
follows:
60+
61+
.. code-block:: java
62+
63+
Bson updateDocument = Updates.operator(field, value);
64+
65+
See the MongoDB API documentation for a :java-core-api:`complete list of
66+
Updates builders and their usage <com/mongodb/client/model/Updates.html>`.
67+
68+
Example
69+
~~~~~~~
70+
71+
The paint store receives a fresh shipment and needs to update their inventory.
72+
The shipment contains 20 cans of each paint color.
73+
74+
To update the inventory, call the ``updateMany()`` method specifying the
75+
following:
76+
77+
- A query filter that matches all the colors
78+
- An update document that contains instructions to increment the ``qty`` field by "20"
79+
80+
.. literalinclude:: /includes/fundamentals/code-snippets/Update.java
81+
:language: java
82+
:dedent:
83+
:start-after: begin updateManyExample
84+
:end-before: end updateManyExample
85+
86+
Your output should look something like this:
87+
88+
.. code-block:: none
89+
90+
Matched document count: 5
91+
Modified document count: 5
92+
93+
The following shows the updated documents in the ``paint_inventory`` collection:
94+
95+
.. code-block:: json
96+
97+
{ "_id": 1, "color": "red", "qty": 25 }
98+
{ "_id": 2, "color": "purple", "qty": 28 }
99+
{ "_id": 3, "color": "yellow", "qty": 20 }
100+
{ "_id": 4, "color": "green", "qty": 26 }
101+
{ "_id": 5, "color": "pink", "qty": 20 }
102+
103+
If zero documents match the query filter in the update operation,
104+
``updateMany()`` makes no changes to documents in the collection. See
105+
our :doc:`upsert guide </fundamentals/crud/write-operations/upsert>` to
106+
learn how to insert a new document instead of updating one if no
107+
documents match.
108+
109+
.. note::
110+
111+
The ``updateOne()`` and ``updateMany()`` methods cannot make changes
112+
to a document that violate unique index constraints on the
113+
collection. See the MongoDB server manual for more information on
114+
:manual:`unique indexes </core/index-unique/>`.
115+
116+
.. _replace-operation:
117+
118+
Replace
119+
-------
120+
121+
A replace operation substitutes one document from your collection. The
122+
substitution occurs between a document your query filter matches and a
123+
replacement document.
124+
125+
The :java-docs:`replaceOne() <apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#replaceOne(org.bson.conversions.Bson,TDocument)>`
126+
method removes all the existing fields and values in the
127+
matching document (except the ``_id`` field) and substitutes it with the
128+
replacement document.
129+
130+
You can call the ``replaceOne()`` method on a ``MongoCollection``
131+
instance as follows:
132+
133+
.. code-block:: java
134+
135+
collection.replaceOne(query, replacementDocument);
136+
137+
Replace Operation Parameters:
138+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
139+
140+
- ``query`` specifies a query filter with the criteria to match a document to replace in your collection
141+
- ``replacementDocument`` specifies fields and values of a new ``Document`` object to replace in the matched document
142+
143+
Example
144+
~~~~~~~
145+
146+
The paint store realizes they need to update their inventory again. What they
147+
thought was 20 cans of pink paint is actually 25 cans of orange paint.
148+
149+
To update the inventory, call the ``replaceOne()`` method specifying the
150+
following:
151+
152+
- A query filter that matches the ``color`` is "pink"
153+
- A replacement document that contains: ``color`` is "orange" and ``qty`` is "25"
154+
155+
.. literalinclude:: /includes/fundamentals/code-snippets/Update.java
156+
:language: java
157+
:dedent:
158+
:start-after: begin replaceOneExample
159+
:end-before: end replaceOneExample
160+
161+
Your output should look something like this:
162+
163+
.. code-block:: none
164+
165+
Matched document count: 1
166+
Modified document count: 1
167+
168+
The following shows the updated document:
169+
170+
.. code-block:: json
171+
172+
{ "_id": 5, "color": "orange", "qty": 25 }
173+
174+
If zero documents match the query filter in the replace operation,
175+
``replaceOne()`` makes no changes to documents in the collection. See
176+
our :doc:`upsert guide </fundamentals/crud/write-operations/upsert>` to
177+
learn how to insert a new document instead of replacing one if no
178+
documents match.
179+
180+
If multiple documents match the query filter specified in
181+
the ``replaceOne()`` method, it replaces the first result.
182+
183+
.. note::
184+
185+
The ``replaceOne()`` method cannot make changes to a document that
186+
violate unique index constraints on the collection. See the MongoDB
187+
server manual for more information on :manual:`unique indexes </core/index-unique/>`.
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
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+
8+
import org.bson.Document;
9+
import org.bson.conversions.Bson;
10+
11+
import java.util.Arrays;
12+
13+
import com.mongodb.client.model.Filters;
14+
import com.mongodb.client.model.Updates;
15+
import com.mongodb.client.result.UpdateResult;
16+
17+
public class Update {
18+
private final MongoCollection<Document> collection;
19+
private final MongoClient mongoClient;
20+
private final MongoDatabase database;
21+
22+
private Update() {
23+
final String uri = System.getenv("DRIVER_REF_URI");
24+
25+
mongoClient = MongoClients.create(uri);
26+
database = mongoClient.getDatabase("crudOps");
27+
collection = database.getCollection("update");
28+
}
29+
30+
public static void main(String [] args){
31+
Update update = new Update();
32+
update.preview(true);
33+
update.setupPaintCollection();
34+
35+
System.out.println("Update Many:");
36+
update.updateManyExample();
37+
update.preview(false);
38+
39+
System.out.println("Replace One:");
40+
update.replaceOneExample();
41+
update.preview(false);
42+
}
43+
44+
private void updateManyExample(){
45+
// begin updateManyExample
46+
Bson filter = Filters.empty();
47+
Bson update = Updates.inc("qty", 20);
48+
UpdateResult result = collection.updateMany(filter, update);
49+
System.out.println("Matched document count: " + result.getMatchedCount());
50+
System.out.println("Modified document count: " + result.getModifiedCount());
51+
// end updateManyExample
52+
}
53+
54+
private void replaceOneExample(){
55+
// begin replaceOneExample
56+
Bson filter = Filters.eq("color", "pink");
57+
Document document = new Document("color", "orange").append("qty", 25);
58+
UpdateResult result = collection.replaceOne(filter, document);
59+
System.out.println("Matched document count: " + result.getMatchedCount());
60+
System.out.println("Modified document count: " + result.getModifiedCount());
61+
// end replaceOneExample
62+
}
63+
64+
private void preview(boolean drop){
65+
Bson filter = Filters.empty();
66+
collection.find(filter).forEach(doc -> System.out.println(doc.toJson()));
67+
if (drop){
68+
collection.drop();
69+
}
70+
}
71+
72+
private void setupPaintCollection() {
73+
74+
collection.insertMany(Arrays.asList(
75+
new Document("_id", 1).append("color", "red").append("qty", 5),
76+
new Document("_id", 2).append("color", "purple").append("qty", 8),
77+
new Document("_id", 3).append("color", "yellow").append("qty", 0),
78+
new Document("_id", 4).append("color", "green").append("qty", 6),
79+
new Document("_id", 5).append("color", "pink").append("qty", 0)
80+
));
81+
}
82+
83+
}

0 commit comments

Comments
 (0)