Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs 菜单
Docs 主页
/ /

更新文档中的数组

在本指南中,您可以学习如何使用Rust驱动程序更新MongoDB文档中的数组字段。

要更新文档中的数组,可以使用更新操作符位置操作符。更新操作符指定要执行的更新类型,位置操作符指定要更新的数组元素。

本指南中的示例使用 students集合中的以下示例文档:

{ "_id": 1, "student": "Kai Ling", "test_scores": [88, 62, 73] },
{ "_id": 2, "student": "Francesca Miao", "test_scores": [95, 45, 67] }

使用位置操作符$更新与查询筛选条件匹配的第一个数组元素。$操作符表示数组中第一个匹配元素的位置。

以下示例使用 update_one() 方法查找其中 test_scores数组包含值 62 的文档。然后,该示例使用位置运算操作符将第一个匹配元素从 62更新为 65

let filter = doc! { "test_scores": 62 };
let update = doc! { "$set": { "test_scores.$": 65 } };
let res = my_coll
.update_one(filter, update)
.await?;
println!("Modified documents: {}", res.modified_count);
Modified documents: 1

以下文档反映了上述更新操作导致的变更:

{ "_id": 1, "student": "Kai Ling", "test_scores": [88, 65, 73] }

使用所有位置操作符$[]更新数组字段中的所有元素。$[]操作符表示更新适用于数组中的每个元素。

以下示例使用 update_one() 方法查找 student字段值为 "Kai Ling" 的文档。然后,该示例使用 all 位置操作符将 test_scores数组中的每个值递增 5

let filter = doc! { "student": "Kai Ling" };
let update = doc! { "$inc": { "test_scores.$[]": 5 } };
let res = my_coll
.update_one(filter, update)
.await?;
println!("Modified documents: {}", res.modified_count);
Modified documents: 1

前面的更新操作会生成类似于以下内容的文档:

{ "_id": 1, "student": "Kai Ling", "test_scores": [93, 67, 78] }

使用筛选后的位置操作符$[<identifier>]更新与数组过滤器匹配的所有数组元素。数组过滤器是指定要更新哪些数组元素的文档。将 <identifier> 设置为占位符名称,然后在数组过滤器中引用该占位符名称。

要使用筛选后的位置操作符,请将 array_filters() 方法链接到您的更新方法调用,并传入过滤文档数组。

以下示例使用 update_many() 方法查找 students集合中的所有文档。然后,该示例使用过滤后的位置操作符符将 8 点添加到所有小于 70test_scores 值:

let filter = doc! {};
let update = doc! { "$inc": { "test_scores.$[score]": 8 } };
let res = my_coll
.update_many(filter, update)
.array_filters(vec![doc! { "score": { "$lt": 70 } }])
.await?;
println!("Modified documents: {}", res.modified_count);
Modified documents: 2

前面的更新操作会生成类似于以下内容的文档:

{ "_id": 1, "student": "Kai Ling", "test_scores": [88, 70, 73] },
{ "_id": 2, "student": "Francesca Miao", "test_scores": [95, 53, 75] }

有关本指南中概念的更多信息,请参阅以下文档:

  • 更新文档指南

  • 指定查询指南

要学习;了解有关本指南中提及的操作符的更多信息,请参阅以下MongoDB Server手册文档:

  • $(更新操作符)

  • $[](更新操作符)

  • $[<identifier>](更新操作符)

  • 数组更新运算符

要进一步了解本指南所提及的方法和类型,请参阅以下 API 文档:

后退

替换文档

在此页面上