[英]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.