Skip to content

Commit b4828b8

Browse files
DOCSP-9565 crud upsert (#71)
* added CRUD Upsert
1 parent fee121f commit b4828b8

File tree

2 files changed

+173
-6
lines changed

2 files changed

+173
-6
lines changed

source/fundamentals/crud/write-operations/upsert.txt

Lines changed: 90 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,94 @@
22
Insert or Update in a Single Operation
33
======================================
44

5-
.. default-domain:: mongodb
5+
Applications use insert and update operations to store and modify data.
6+
Sometimes, you need to choose between an insert and update depending on
7+
whether the document exists. MongoDB simplifies this decision for us
8+
with an ``upsert`` option.
69

7-
If your application stores and modifies data in MongoDB, you probably use
8-
insert and update operations. In certain workflows, you may need to choose
9-
between an insert and update depending on whether the document exists.
10-
In these cases, you can streamline your application logic by using the
11-
``upsert`` option available in the following methods:
10+
An ``upsert``:
11+
12+
- Updates documents that match your query filter
13+
- Inserts a document if there are no matches to your query filter
14+
15+
Specify an Upsert:
16+
------------------
17+
18+
To specify an upsert with the ``updateOne()`` or ``updateMany()``
19+
methods, pass ``true`` to :java-docs:`UpdateOptions.upsert()
20+
</apidocs/mongodb-driver-core/com/mongodb/client/model/UpdateOptions.html#upsert(boolean)>`.
21+
22+
To specify an upsert with the ``replaceOne()`` method, pass ``true`` to
23+
:java-docs:`ReplaceOptions.upsert()
24+
</apidocs/mongodb-driver-core/com/mongodb/client/model/ReplaceOptions.html#upsert(boolean)>`.
25+
26+
In the following example, a paint store sells eight different
27+
colors of paint. The store had their annual online sale. Their
28+
``paint_inventory`` collection now shows the following documents:
29+
30+
.. code-block:: json
31+
32+
{ "_id": { "$oid": "606b4cfbcd83be7518b958da" }, "color": "red", "qty": 5 }
33+
{ "_id": { "$oid": "606b4cfbcd83be7518b958db" }, "color": "purple", "qty": 8 }
34+
{ "_id": { "$oid": "606b4cfbcd83be7518b958dc" }, "color": "blue", "qty": 0 }
35+
{ "_id": { "$oid": "606b4cfbcd83be7518b958dd" }, "color": "white", "qty": 0 }
36+
{ "_id": { "$oid": "606b4cfbcd83be7518b958de" }, "color": "yellow", "qty": 6 }
37+
{ "_id": { "$oid": "606b4cfbcd83be7518b958df" }, "color": "pink", "qty": 0 }
38+
{ "_id": { "$oid": "606b4cfbcd83be7518b958e0" }, "color": "green", "qty": 0 }
39+
{ "_id": { "$oid": "606b4cfbcd83be7518b958e1" }, "color": "black", "qty": 8 }
40+
41+
The store received a fresh shipment and needs to update their inventory.
42+
The first item in the shipment is ten cans of orange paint.
43+
44+
To update the inventory, query the ``paint_inventory`` collection
45+
where the ``color`` is ``"orange"``, specify an update to ``increment`` the
46+
``qty`` field by ``10``, and specify ``true`` to
47+
``UpdateOptions.upsert()``:
48+
49+
.. literalinclude:: /includes/fundamentals/code-snippets/InsertUpdate.java
50+
:language: java
51+
:dedent:
52+
:start-after: begin updateOneExample
53+
:end-before: end updateOneExample
54+
55+
The method returns:
56+
57+
.. code-block:: json
58+
59+
AcknowledgedUpdateResult{ matchedCount=0, modifiedCount=0, upsertedId=BsonObjectId{ value=606b4cfc1601f9443b5d6978 }}
60+
61+
This ``AcknowledgedUpdateResult`` tells us:
62+
63+
- Zero documents matched our query filter
64+
- Zero documents in our collection got modified
65+
- A document with an ``_id`` of ``606b4cfc1601f9443b5d6978`` got upserted
66+
67+
The following shows the documents in the ``paint_inventory`` collection:
68+
69+
.. code-block:: json
70+
71+
{ "_id": { "$oid": "606b4cfbcd83be7518b958da" }, "color": "red", "qty": 5 }
72+
{ "_id": { "$oid": "606b4cfbcd83be7518b958db" }, "color": "purple", "qty": 8 }
73+
{ "_id": { "$oid": "606b4cfbcd83be7518b958dc" }, "color": "blue", "qty": 0 }
74+
{ "_id": { "$oid": "606b4cfbcd83be7518b958dd" }, "color": "white", "qty": 0 }
75+
{ "_id": { "$oid": "606b4cfbcd83be7518b958de" }, "color": "yellow", "qty": 6 }
76+
{ "_id": { "$oid": "606b4cfbcd83be7518b958df" }, "color": "pink", "qty": 0 }
77+
{ "_id": { "$oid": "606b4cfbcd83be7518b958e0" }, "color": "green", "qty": 0 }
78+
{ "_id": { "$oid": "606b4cfbcd83be7518b958e1" }, "color": "black", "qty": 8 }
79+
{ "_id": { "$oid": "606b4cfc1601f9443b5d6978" }, "color": "orange", "qty": 10 }]
80+
81+
.. note::
82+
83+
Not including ``UpdateOptions`` results in no change to the collection.
84+
85+
.. literalinclude:: /includes/fundamentals/code-snippets/InsertUpdate.java
86+
:language: java
87+
:dedent:
88+
:start-after: begin updateOneAttemptExample
89+
:end-before: end updateOneAttemptExample
90+
91+
The method returns:
92+
93+
.. code-block:: json
94+
95+
AcknowledgedUpdateResult{ matchedCount=0, modifiedCount=0, upsertedId=null }
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.UpdateOptions;
15+
import com.mongodb.client.model.Updates;
16+
17+
public class InsertUpdate {
18+
19+
private final MongoCollection<Document> collection;
20+
private final MongoClient mongoClient;
21+
private final MongoDatabase database;
22+
23+
private InsertUpdate() {
24+
final String uri = System.getenv("DRIVER_REF_URI");
25+
26+
mongoClient = MongoClients.create(uri);
27+
database = mongoClient.getDatabase("crudOps");
28+
collection = database.getCollection("upsert");
29+
}
30+
31+
public static void main(String [] args){
32+
InsertUpdate insertUpdate = new InsertUpdate();
33+
insertUpdate.preview(true);
34+
insertUpdate.setupPaintCollection();
35+
36+
System.out.println("Update One Attempt:");
37+
insertUpdate.updateOneAttemptExample();
38+
insertUpdate.preview(false);
39+
40+
System.out.println("Update One:");
41+
insertUpdate.updateOneExample();
42+
insertUpdate.preview(false);
43+
}
44+
45+
private void updateOneAttemptExample(){
46+
// begin updateOneAttemptExample
47+
Bson filter = Filters.eq("color", "orange");
48+
Bson update = Updates.inc("qty", 10);
49+
System.out.println(collection.updateOne(filter, update));
50+
// end updateOneAttemptExample
51+
}
52+
53+
private void updateOneExample(){
54+
// begin updateOneExample
55+
Bson filter = Filters.eq("color", "orange");
56+
Bson update = Updates.inc("qty", 10);
57+
UpdateOptions options = new UpdateOptions().upsert(true);
58+
System.out.println(collection.updateOne(filter, update, options));
59+
// end updateOneExample
60+
}
61+
62+
private void preview(boolean drop){
63+
Bson filter = Filters.empty();
64+
collection.find(filter).forEach(doc -> System.out.println(doc.toJson()));
65+
if (drop){
66+
collection.drop();
67+
}
68+
}
69+
70+
private void setupPaintCollection() {
71+
72+
collection.insertMany(Arrays.asList(
73+
new Document("color", "red").append("qty", 5),
74+
new Document("color", "purple").append("qty", 8),
75+
new Document("color", "blue").append("qty", 0),
76+
new Document("color", "white").append("qty", 0),
77+
new Document("color", "yellow").append("qty", 6),
78+
new Document("color", "pink").append("qty", 0),
79+
new Document("color", "green").append("qty", 0),
80+
new Document("color", "black").append("qty", 8)
81+
));
82+
}
83+
}

0 commit comments

Comments
 (0)