如何使用 MongoDB Java 驱动程序更新数组中的对象?

jaf*_*yed 7 java spring mongodb mongodb-java mongodb-atlas

你好,我有这份文件

{
  email: "email@gmail.com",
  list: [
    {
      "product": "Car",
      "price": 18
    },
    {
      "product": "Boat",
      "price": 20 
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我想知道如何使用参数识别文档,并通过查找具有“Car”参数的产品并使用 MongoDB Java 驱动程序将价格email更新为 15 来更新参数中的特定对象。list

谢谢

pra*_*ad_ 8

有两种方法可以根据条件更新数组字段的嵌套文档。

(1) 使用位置 $ 运算符更新:

位置$ 运算符充当与查询文档匹配的第一个元素的占位符,并且数组字段必须作为查询文档的一部分出现;即"list.product": "Car". 其次,只有第一个匹配的数组元素才会被更新。

db.collection.updateOne( 
  { email: "email@gmail.com", "list.product": "Car" }, 
  { $set: { "list.$.price": 15 } } 
)
Run Code Online (Sandbox Code Playgroud)

(2) 使用过滤位置 $[identifier] 运算符更新:

过滤后的位置运算符 $[identifier]arrayFilters标识与更新操作条件匹配的数组元素。

请注意,使用更新运算符时不需要数组字段上的条件$[identifier]。其次,所有匹配的数组元素 ( "product": "Car") 将被更新。

db.collection.updateOne( 
  { email: "email@gmail.com" }, 
  { $set: { "list.$[ele].price": 15 } },
  { arrayFilters: [ { "ele.product": "Car" } ] }
)
Run Code Online (Sandbox Code Playgroud)

使用 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);
Run Code Online (Sandbox Code Playgroud)

案例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);
Run Code Online (Sandbox Code Playgroud)

参考: MongoDB Java 驱动程序