MongoDB 专用数据操作方法
除了查询方法之外,还可以使用专用方法来更新数据。
更新方法
您也可以使用前述表格中的关键词来创建查询,以标识匹配的文档并对其执行更新。实际的更新动作由方法上的 @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
}
仓库更新不会触发持久化事件,也不会触发映射生命周期事件。
删除方法
前述表格中的关键词可以与 delete…By 或 remove…By 结合使用,以创建删除匹配文档的查询。
- Imperative
- Reactive
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
Listretrieves 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
Optionaltype.
public interface PersonRepository extends ReactiveMongoRepository<Person, String> {
Flux<Person> deleteByLastname(String lastname); 1
Mono<Long> deletePersonByLastname(String lastname); 2
Mono<Person> deleteSingleByLastname(String lastname); 3
}
Using a return type of
Fluxretrieves 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.