Skip to content

Commit 27e13e7

Browse files
committed
modify
1 parent f7757d2 commit 27e13e7

File tree

4 files changed

+147
-12
lines changed

4 files changed

+147
-12
lines changed

source/crud/update-documents.txt

Lines changed: 116 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,4 +170,119 @@ documents match.
170170
to a document that violate unique index constraints on the
171171
collection. For more information about constraints on unique indexes,
172172
see :manual:`Unique Indexes </core/index-unique/>` in the
173-
{+mdb-server+} manual.
173+
{+mdb-server+} manual.
174+
175+
Update Example
176+
~~~~~~~~~~~~~~
177+
178+
The following code is a complete, standalone file that performs an update one
179+
operation and an update many operation.
180+
181+
.. include:: /includes/crud/example-intro.rst
182+
183+
.. io-code-block::
184+
185+
.. input:: /includes/crud/Insert.java
186+
:language: java
187+
:dedent:
188+
189+
.. output::
190+
:language: none
191+
:visible: false
192+
193+
InsertOne document id: BsonObjectId{value=...}
194+
InsertMany document ids: {0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}}
195+
196+
.. _replace-operation:
197+
198+
Replace
199+
-------
200+
201+
A replace operation substitutes one document from your collection. The
202+
substitution occurs between a document your query filter matches and a
203+
replacement document.
204+
205+
The `replaceOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#replaceOne(org.bson.conversions.Bson,TDocument)>`__
206+
method removes all the existing fields and values in the
207+
matching document (except the ``_id`` field) and substitutes it with the
208+
replacement document.
209+
210+
You can call the ``replaceOne()`` method on a ``MongoCollection``
211+
instance as follows:
212+
213+
.. code-block:: java
214+
215+
collection.replaceOne(<query>, <replacement>);
216+
217+
Replace Operation Parameters
218+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
219+
220+
The ``replaceOne()`` method has the following parameters:
221+
222+
- ``query`` specifies a query filter with the criteria to match a
223+
document to replace in your collection.
224+
- ``replacement`` specifies fields and values of a new ``Document``
225+
object to replace the matched document.
226+
- *(Optional)* ``replaceOptions`` specifies options that you can set to
227+
customize how the driver performs the replace operation. To learn more
228+
about this type, see the API documentation for `ReplaceOptions
229+
<{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/ReplaceOptions.html>`__.
230+
231+
Replace One Example
232+
~~~~~~~~~~~~~~~~~~~
233+
234+
The paint store realizes they must update their inventory again. What they
235+
thought was 20 cans of pink paint is actually 25 cans of orange paint.
236+
237+
To update the inventory, call the ``replaceOne()`` method specifying the
238+
following:
239+
240+
- A query filter that matches documents where the ``color`` is "pink"
241+
- A replacement document where the ``color`` is "orange" and the ``qty`` is "25"
242+
243+
.. literalinclude:: /includes/fundamentals/code-snippets/Update.java
244+
:language: java
245+
:dedent:
246+
:start-after: begin replaceOneExample
247+
:end-before: end replaceOneExample
248+
249+
The output of the preceding code resembles the following:
250+
251+
.. code-block:: none
252+
:copyable: false
253+
254+
Matched document count: 1
255+
Modified document count: 1
256+
257+
The following shows the updated document:
258+
259+
.. code-block:: json
260+
:copyable: false
261+
262+
{ "_id": 5, "color": "orange", "qty": 25 }
263+
264+
If multiple documents match the query filter specified in
265+
the ``replaceOne()`` method, it replaces the first result. You can
266+
specify a sort in a ``ReplaceOptions`` instance to apply an order to
267+
matched documents before the server performs the replace operation, as
268+
shown in the following code:
269+
270+
.. literalinclude:: /includes/fundamentals/code-snippets/Update.java
271+
:language: java
272+
:dedent:
273+
:start-after: begin replaceoptions
274+
:end-before: end replaceoptions
275+
276+
If zero documents match the query filter in the replace operation,
277+
``replaceOne()`` makes no changes to documents in the collection. See
278+
our :ref:`upsert guide <java-upsert>` to
279+
learn how to insert a new document instead of replacing one if no
280+
documents match.
281+
282+
.. important::
283+
284+
The ``replaceOne()`` method cannot make changes to a document that
285+
violate unique index constraints on the collection.
286+
For more information about constraints on unique indexes,
287+
see :manual:`Unique Indexes </core/index-unique/>` in the
288+
{+mdb-server+} manual.

source/includes/crud/Delete.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@ public static void main(String[] args) {
2929

3030
try {
3131
// Deletes the first document that has a "title" value of "The Garbage Pail Kids Movie"
32-
DeleteResult deleteOneResult = collection.deleteOne(deleteOneQuery);
33-
System.out.println("DeleteOne document count: " + deleteOneResult.getDeletedCount());
32+
DeleteResult result = collection.deleteOne(deleteOneQuery);
33+
System.out.println("DeleteOne document count: " + result.getDeletedCount());
3434

3535
// Prints a message if any exceptions occur during the operation
3636
} catch (MongoException me) {
@@ -41,10 +41,10 @@ public static void main(String[] args) {
4141

4242
try {
4343
// Deletes all documents that have an "imdb.rating" value less than 1.9
44-
DeleteResult deleteManyResult = collection.deleteMany(deleteManyQuery);
44+
DeleteResult result = collection.deleteMany(deleteManyQuery);
4545

4646
// Prints the number of deleted documents
47-
System.out.println("DeleteMany document count: " + deleteManyResult.getDeletedCount());
47+
System.out.println("DeleteMany document count: " + result.getDeletedCount());
4848

4949
// Prints a message if any exceptions occur during the operation
5050
} catch (MongoException me) {

source/includes/crud/Insert.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public static void main(String[] args) {
2626

2727
try {
2828
// Inserts a sample document describing a movie into the collection
29-
InsertOneResult iOResult = collection.insertOne(new Document()
29+
InsertOneResult result = collection.insertOne(new Document()
3030
.append("_id", new ObjectId())
3131
.append("title", "Ski Bloopers")
3232
.append("genres", Arrays.asList("Documentary", "Comedy")));

source/includes/usage-examples/code-snippets/UpdateOne.java renamed to source/includes/crud/Update.java

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,20 +24,21 @@ public static void main(String[] args) {
2424
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
2525
MongoCollection<Document> collection = database.getCollection("movies");
2626

27-
Document query = new Document().append("title", "Cool Runnings 2");
27+
// Instructs the driver to insert a new document if none match the query
28+
UpdateOptions options = new UpdateOptions().upsert(true);
29+
30+
31+
Document updateOneQuery = new Document().append("title", "Cool Runnings 2");
2832

2933
// Creates instructions to update the values of three document fields
30-
Bson updates = Updates.combine(
34+
Bson updateOneUpdates = Updates.combine(
3135
Updates.set("runtime", 99),
3236
Updates.addToSet("genres", "Sports"),
3337
Updates.currentTimestamp("lastUpdated"));
3438

35-
// Instructs the driver to insert a new document if none match the query
36-
UpdateOptions options = new UpdateOptions().upsert(true);
37-
3839
try {
3940
// Updates the first document that has a "title" value of "Cool Runnings 2"
40-
UpdateResult result = collection.updateOne(query, updates, options);
41+
UpdateResult result = collection.updateOne(updateOneQuery, updateOneUpdates, options);
4142

4243
// Prints the number of updated documents and the upserted document ID, if an upsert was performed
4344
System.out.println("Modified document count: " + result.getModifiedCount());
@@ -47,6 +48,25 @@ public static void main(String[] args) {
4748
} catch (MongoException me) {
4849
System.err.println("Unable to update due to an error: " + me);
4950
}
51+
52+
Bson updateManyQuery = gt("num_mflix_comments", 50);
53+
54+
// Creates instructions to update the values of two document fields
55+
Bson updateManyUpdates = Updates.combine(
56+
Updates.addToSet("genres", "Frequently Discussed"),
57+
Updates.currentTimestamp("lastUpdated"));
58+
59+
try {
60+
// Updates documents that have a "num_mflix_comments" value over 50
61+
UpdateResult result = collection.updateMany(updateManyQuery, updateManyUpdates);
62+
63+
// Prints the number of updated documents
64+
System.out.println("Modified document count: " + result.getModifiedCount());
65+
66+
// Prints a message if any exceptions occur during the operation
67+
} catch (MongoException me) {
68+
System.err.println("Unable to update due to an error: " + me);
69+
}
5070
}
5171
}
5272
}

0 commit comments

Comments
 (0)