[英]How to update an object in a array using MongoDB Java Driver?
Hello I have this document你好,我有这份文件
{
email: "email@gmail.com",
list: [
{
"product": "Car",
"price": 18
},
{
"product": "Boat",
"price": 20
}
]
}
I am wondering how to identify the document using the email
parameter and update a specific object in the list
parameter by finding the product with the "Car" parameter and updating the price to 15 using the MongoDB Java Driver.我想知道如何使用
email
参数识别文档并通过查找具有“Car”参数的产品并使用 MongoDB Java 驱动程序将价格更新为 15 来更新list
参数中的特定 object。
Thank you谢谢
There are two ways to update the nested document of an array field based upon a condition.有两种方法可以根据条件更新数组字段的嵌套文档。
(1) Update using the Positional $ Operator: (1) 使用位置 $ 运算符更新:
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;ie, "list.product": "Car"
. 位置 $ 运算符充当与查询文档匹配的第一个元素的占位符,数组字段必须作为查询文档的一部分出现;即
"list.product": "Car"
。 And, secondly only the first matching array element will be updated.其次,只有第一个匹配的数组元素会被更新。
db.collection.updateOne(
{ email: "email@gmail.com", "list.product": "Car" },
{ $set: { "list.$.price": 15 } }
)
(2) Update using the Filtered Positional $[identifier] Operator: (2) 使用 Filtered Positional $[identifier] Operator 进行更新:
The filtered positional operator $[identifier] identifies the array elements that match the arrayFilters
conditions for an update operation. 过滤后的位置运算符 $[identifier]标识与更新操作的
arrayFilters
条件匹配的数组元素。
Note the condition on the array field is not required when using the $[identifier]
update operator.请注意,使用
$[identifier]
更新运算符时不需要数组字段上的条件。 And, secondly all the matching array elements ( "product": "Car"
) will be updated.其次,所有匹配的数组元素 (
"product": "Car"
) 都将更新。
db.collection.updateOne(
{ email: "email@gmail.com" },
{ $set: { "list.$[ele].price": 15 } },
{ arrayFilters: [ { "ele.product": "Car" } ] }
)
Update using MongoDB Java Driver:使用 MongoDB Java 驱动更新:
Case 1:情况1:
Bson filter = and(eq("email", "email@gmail.com"), eq("list.product", "Car"));
Bson update = set("list.$.price", 15);
UpdateResult result = coll.updateOne(filter, update);
Case 2:案例二:
Bson filter = eq("email", "email@gmail.com");
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参考: MongoDB Java 司机
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.