跳到主要内容
版本:5.1.1

MongoDB 专用数据操作方法

Doubao 中英对照 MongoDB-specific Data Manipulation Methods

除了查询方法之外,还可以使用专用方法来更新数据。

更新方法​

您也可以使用前述表格中的关键词来创建查询,以标识匹配的文档并对其执行更新。实际的更新动作由方法上的 @Update 注解定义,如下例所示。请注意,派生查询的命名模式以 find 开头。只有与 @Query 结合使用时才允许使用 update(如 updateAllByLastname(…))。

更新会应用到所有匹配的文档,并且无法通过传入 Page 或使用任何限制关键词来限定范围。返回类型可以是 void,也可以是一个_数值_类型(如 long),用于保存被修改的文档数。

示例 1. 更新方法

public interface PersonRepository extends CrudRepository<Person, String> {

@Update("{ '$inc' : { 'visits' : 1 } }")
long findAndIncrementVisitsByLastname(String lastname); 1

@Update("{ '$inc' : { 'visits' : ?1 } }")
void findAndIncrementVisitsByLastname(String lastname, int increment); 2

@Update("{ '$inc' : { 'visits' : ?#{[1]} } }")
long findAndIncrementVisitsUsingSpELByLastname(String lastname, int increment); 3

@Update(pipeline = {"{ '$set' : { 'visits' : { '$add' : [ '$visits', ?1 ] } } }"})
void findAndIncrementVisitsViaPipelineByLastname(String lastname, int increment); 4

@Update("{ '$push' : { 'shippingAddresses' : ?1 } }")
long findAndPushShippingAddressByEmail(String email, Address address); 5

@Query("{ 'lastname' : ?0 }")
@Update("{ '$inc' : { 'visits' : ?1 } }")
void updateAllByLastname(String lastname, int increment); 6
}
  • 更新所用的过滤查询派生自方法名。该更新“按原样”执行,不绑定任何参数。

  • 实际的递增值由 increment 方法参数定义,该参数绑定到 ?1 占位符。

  • 使用 Spring 表达式语言(SpEL)进行参数绑定。

  • 使用 pipeline 属性来发起聚合管道更新。

  • 更新可以包含复杂对象。

  • 将基于字符串的查询与更新结合使用。

注意

仓库更新不会触发持久化事件,也不会触发映射生命周期事件。

删除方法​

前述表格中的关键词可以与 delete…By 或 remove…By 结合使用,以创建删除匹配文档的查询。

public interface PersonRepository extends MongoRepository<Person, String> {

List <Person> deleteByLastname(String lastname); 1

Long deletePersonByLastname(String lastname); 2

@Nullable
Person deleteSingleByLastname(String lastname); 3

Optional<Person> deleteByBirthdate(Date birthdate); 4
}
  • Using a return type of List retrieves and returns all matching documents before actually deleting them.

  • A numeric return type directly removes the matching documents, returning the total number of documents removed.

  • A single domain type result retrieves and removes the first matching document.

  • Same as in 3 but wrapped in an Optional type.