Skip to content

Commit 1611905

Browse files
DOCSP-9564 crud update array (#79)
* added Update Embedded Arrays page
1 parent 41963da commit 1611905

File tree

3 files changed

+291
-6
lines changed

3 files changed

+291
-6
lines changed

source/fundamentals/crud/write-operations.txt

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,14 @@ Write Operations
77
- :doc:`/fundamentals/crud/write-operations/insert`
88
- :doc:`/fundamentals/crud/write-operations/delete`
99
- :doc:`/fundamentals/crud/write-operations/change-a-document`
10+
- :doc:`/fundamentals/crud/write-operations/embedded-arrays`
1011
- :doc:`/fundamentals/crud/write-operations/upsert`
1112

12-
..
13-
- :doc:`/fundamentals/crud/write-operations/embedded-arrays`
14-
1513
.. toctree::
1614
:caption: Write Operations
1715

1816
/fundamentals/crud/write-operations/insert
1917
/fundamentals/crud/write-operations/delete
2018
/fundamentals/crud/write-operations/change-a-document
19+
/fundamentals/crud/write-operations/embedded-arrays
2120
/fundamentals/crud/write-operations/upsert
22-
23-
..
24-
/fundamentals/crud/write-operations/embedded-arrays
Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
===========================
2+
Update Arrays in a Document
3+
===========================
4+
5+
.. default-domain:: mongodb
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
Overview
14+
--------
15+
16+
In this guide, you will learn how to update arrays in a document.
17+
18+
To update an array, you must do the following:
19+
20+
- Specify the update you want to perform
21+
- Specify what array elements to apply your update to
22+
- Perform an update operation using these specifications
23+
24+
Sample Document
25+
~~~~~~~~~~~~~~~
26+
27+
The following sections feature examples that update this sample
28+
document:
29+
30+
.. code-block:: json
31+
32+
{ "_id": 1, "color": "green", "qty": [8, 12, 18] }
33+
34+
The examples on this page use the ``findOneAndUpdate()`` method of the
35+
``MongoCollection`` class to retrieve and update the document. Each
36+
example uses an instance of the ``FindOneAndUpdateOptions`` class to
37+
have MongoDB retrieve the document after the update occurs. For
38+
more information on the ``findOneAndUpdate()`` method, see our Compound
39+
Operations guide <TODO>.
40+
41+
Specifying an Update
42+
--------------------
43+
44+
To specify an update, use the ``Updates`` builder. The ``Updates``
45+
builder provides static utility methods to construct update
46+
specifications. For more information on using the ``Updates`` builder with
47+
arrays, see our :ref:`guide on the Updates builder <array_updates>`.
48+
49+
The following example performs these actions:
50+
51+
- Query for the sample document
52+
- Add "17" to the ``qty`` array using the ``push()`` method of the ``Updates`` builder
53+
54+
.. literalinclude:: /includes/fundamentals/code-snippets/UpdateArray.java
55+
:language: java
56+
:dedent:
57+
:start-after: begin pushElementsExample
58+
:end-before: end pushElementsExample
59+
60+
The example above updates the original document to the following state:
61+
62+
.. code-block:: json
63+
:copyable: false
64+
65+
{ "_id": 1, "color": "green", "qty": [8, 12, 18, 17] }
66+
67+
Specifying Array Elements
68+
-------------------------
69+
70+
You can specify which array elements to update using a positional
71+
operator. Positional operators can specify the first, all, or certain
72+
array elements to update.
73+
74+
To specify elements in an array with positional operators, use **dot
75+
notation**. Dot notation is a property access syntax for navigating BSON
76+
objects.
77+
78+
For additional information, see the server manual entry on
79+
:manual:`dot notation </core/document/#std-label-document-dot-notation>`.
80+
81+
The First Matching Array Element
82+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
83+
84+
To update the first array element that matches your query filter, use the
85+
positional ``$`` operator. The array field must appear as part of your
86+
query document to use the positional ``$`` operator.
87+
88+
Example
89+
```````
90+
91+
The following example performs these actions:
92+
93+
- Query for a document with a ``qty`` field containing the value "18"
94+
- Decrement the first array value that matches the query document by "3" using the ``inc()`` method of the ``Updates`` builder and the positional ``$`` operator
95+
96+
.. literalinclude:: /includes/fundamentals/code-snippets/UpdateArray.java
97+
:language: java
98+
:dedent:
99+
:start-after: begin updateValueExample
100+
:end-before: end updateValueExample
101+
102+
The example above updates the original document to the following state:
103+
104+
.. code-block:: json
105+
:copyable: false
106+
107+
{ "_id": 1, "color": "green", "qty": [8, 12, 15] }
108+
109+
For additional information on the operator and method mentioned in this
110+
section, see the following resources:
111+
112+
- :manual:`Positional $ Operator </reference/operator/update/positional>` Server Manual Entry
113+
- :java-core-api:`inc() <com/mongodb/client/model/Updates.html#inc(java.lang.String,java.lang.Number)>` API Documentation
114+
115+
Matching All Array Elements
116+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
117+
118+
To update all elements in an array, use the all positional ``$[]`` operator.
119+
120+
Example
121+
```````
122+
123+
The following example performs these actions:
124+
125+
- Query for the sample document
126+
- Multiply array elements matching the filter by "2" using the ``mul()`` method of the ``Updates`` builder and the all positional ``$[]`` operator
127+
128+
.. literalinclude:: /includes/fundamentals/code-snippets/UpdateArray.java
129+
:language: java
130+
:dedent:
131+
:start-after: begin updateAllElementsExample
132+
:end-before: end updateAllElementsExample
133+
134+
The example above updates the original document to the following state:
135+
136+
.. code-block:: json
137+
:copyable: false
138+
139+
{ "_id": 1, "color": "green", "qty": [16, 24, 36] }
140+
141+
For additional information on the operator and method mentioned in this
142+
section, see the following resources:
143+
144+
- :manual:`All Positional $[] Operator </reference/operator/update/positional-all/>` Server Manual Entry
145+
- :java-core-api:`mul() <com/mongodb/client/model/Updates.html#mul(java.lang.String,java.lang.Number)>` API Documentation
146+
147+
Matching Multiple Array Elements
148+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
149+
150+
To update array elements that match a filter, use the
151+
filtered positional ``$[<identifier>]`` operator. You must include an
152+
array filter in your update operation to specify which array elements to
153+
update.
154+
155+
The ``<identifier>`` is the name you give your array filter. This value
156+
must begin with a lowercase letter and contain only alphanumeric
157+
characters.
158+
159+
Example
160+
```````
161+
162+
The following example performs these actions:
163+
164+
- Query for the sample document
165+
- Set an array filter to search for values less than "15"
166+
- Increment array elements matching the filter by "5" using the ``inc()`` method of the ``Updates`` builder and the filtered positional operator
167+
168+
.. literalinclude:: /includes/fundamentals/code-snippets/UpdateArray.java
169+
:language: java
170+
:dedent:
171+
:start-after: begin updateValueOptionsExample
172+
:end-before: end updateValueOptionsExample
173+
174+
The example above updates the original document to the following state:
175+
176+
.. code-block:: json
177+
:copyable: false
178+
179+
{ "_id": 1, "color": "green", "qty": [13, 17, 18] }
180+
181+
For additional information on the operator and method mentioned in this
182+
section, see the following resources:
183+
184+
- :manual:`Positional $[\<identifier\>] Operator </reference/operator/update/positional-filtered/>` Server Manual Entry
185+
- :java-core-api:`inc() <com/mongodb/client/model/Updates.html#inc(java.lang.String,java.lang.Number)>` API Documentation
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
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.FindOneAndUpdateOptions;
15+
import com.mongodb.client.model.ReturnDocument;
16+
import com.mongodb.client.model.Updates;
17+
18+
public class UpdateArray {
19+
private final MongoCollection<Document> collection;
20+
private final MongoClient mongoClient;
21+
private final MongoDatabase database;
22+
23+
private UpdateArray() {
24+
final String uri = System.getenv("DRIVER_REF_URI");
25+
26+
mongoClient = MongoClients.create(uri);
27+
database = mongoClient.getDatabase("crudOps");
28+
collection = database.getCollection("updateArray");
29+
}
30+
31+
public static void main(String [] args){
32+
UpdateArray updateArray = new UpdateArray();
33+
34+
System.out.println("$ example:");
35+
updateArray.setUpDocument();
36+
updateArray.updateValueExample();
37+
38+
System.out.println("$<> example:");
39+
updateArray.setUpDocument();
40+
updateArray.updateValueOptionsExample();
41+
42+
System.out.println("$[] example:");
43+
updateArray.setUpDocument();
44+
updateArray.updateAllElementsExample();
45+
46+
System.out.println("Push example:");
47+
updateArray.setUpDocument();
48+
updateArray.pushElementsExample();
49+
}
50+
51+
private void updateValueExample(){
52+
// begin updateValueExample
53+
Bson filter = Filters.eq("qty", 18);
54+
Bson update = Updates.inc("qty.$", -3);
55+
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions()
56+
.returnDocument(ReturnDocument.AFTER);
57+
Document result = collection.findOneAndUpdate(filter, update, options);
58+
System.out.println(result.toJson());
59+
// end updateValueExample
60+
}
61+
62+
private void updateValueOptionsExample(){
63+
// begin updateValueOptionsExample
64+
Bson filter = Filters.eq("_id", 1);
65+
Bson smallerFilter = Filters.lt("smaller", 15);
66+
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions()
67+
.returnDocument(ReturnDocument.AFTER)
68+
.arrayFilters(Arrays.asList(smallerFilter));
69+
Bson update = Updates.inc("qty.$[smaller]", 5);
70+
71+
Document result = collection.findOneAndUpdate(filter, update, options);
72+
System.out.println(result.toJson());
73+
// end updateValueOptionsExample
74+
}
75+
76+
private void updateAllElementsExample(){
77+
// begin updateAllElementsExample
78+
Bson filter = Filters.eq("_id", 1);
79+
Bson update = Updates.mul("qty.$[]", 2);
80+
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions()
81+
.returnDocument(ReturnDocument.AFTER);
82+
Document result = collection.findOneAndUpdate(filter, update, options);
83+
System.out.println(result.toJson());
84+
// end updateAllElementsExample
85+
}
86+
87+
private void pushElementsExample(){
88+
// begin pushElementsExample
89+
Bson filter = Filters.eq("_id", 1);
90+
Bson update = Updates.push("qty", 17);
91+
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions()
92+
.returnDocument(ReturnDocument.AFTER);
93+
Document result = collection.findOneAndUpdate(filter, update, options);
94+
System.out.println(result.toJson());
95+
// end pushElementsExample
96+
}
97+
98+
private void setUpDocument(){
99+
collection.drop();
100+
collection.insertOne(
101+
Document.parse("{ _id: 1, color: 'green', qty: [ 8, 12, 18 ] }")
102+
);
103+
}
104+
}

0 commit comments

Comments
 (0)