![](/img/trans.png)
[英]How to access object nested inside an array in MongoDB using Java driver
[英]How to update an object in a array using MongoDB Java Driver?
你好,我有这份文件
{
email: "email@gmail.com",
list: [
{
"product": "Car",
"price": 18
},
{
"product": "Boat",
"price": 20
}
]
}
我想知道如何使用email
参数识别文档并通过查找具有“Car”参数的产品并使用 MongoDB Java 驱动程序将价格更新为 15 来更新list
参数中的特定 object。
谢谢
有两种方法可以根据条件更新数组字段的嵌套文档。
(1) 使用位置 $ 运算符更新:
位置 $ 运算符充当与查询文档匹配的第一个元素的占位符,数组字段必须作为查询文档的一部分出现;即"list.product": "Car"
。 其次,只有第一个匹配的数组元素会被更新。
db.collection.updateOne(
{ email: "email@gmail.com", "list.product": "Car" },
{ $set: { "list.$.price": 15 } }
)
(2) 使用 Filtered Positional $[identifier] Operator 进行更新:
过滤后的位置运算符 $[identifier]标识与更新操作的arrayFilters
条件匹配的数组元素。
请注意,使用$[identifier]
更新运算符时不需要数组字段上的条件。 其次,所有匹配的数组元素 ( "product": "Car"
) 都将更新。
db.collection.updateOne(
{ email: "email@gmail.com" },
{ $set: { "list.$[ele].price": 15 } },
{ arrayFilters: [ { "ele.product": "Car" } ] }
)
使用 MongoDB Java 驱动更新:
情况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);
案例二:
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);
参考: MongoDB Java 司机
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.