There are two ways to update the nested document of an array field based upon a condition.
(1) Update using the Positional $ Operator:
The positional $ operator acts as a placeholder for the first element that matches the query document, and the array field must appear as part of the query document;i.e., "list.product": "Car"
. And, secondly only the first matching array element will be updated.
db.collection.updateOne(
{ email: "[email protected]", "list.product": "Car" },
{ $set: { "list.$.price": 15 } }
)
(2) Update using the Filtered Positional $[identifier] Operator:
The filtered positional operator $[identifier] identifies the array elements that match the arrayFilters
conditions for an update operation.
Note the condition on the array field is not required when using the $[identifier]
update operator. And, secondly all the matching array elements ("product": "Car"
) will be updated.
db.collection.updateOne(
{ email: "[email protected]" },
{ $set: { "list.$[ele].price": 15 } },
{ arrayFilters: [ { "ele.product": "Car" } ] }
)
Update using MongoDB Java Driver:
Case 1:
Bson filter = and(eq("email", "[email protected]"), eq("list.product", "Car"));
Bson update = set("list.$.price", 15);
UpdateResult result = coll.updateOne(filter, update);
Case 2:
Bson filter = eq("email", "[email protected]");
UpdateOptions options = new UpdateOptions()
.arrayFilters(asList(eq("ele.product", "Car")));
Bson update = set("list.$[ele].price", 15);
UpdateResult result = coll.updateOne(filter, update, options);
Reference: MongoDB Java Driver