MongoDB 特有的資料操作方法

除了 查詢方法 之外,還可以使用專門的方法更新資料。

更新方法

您還可以使用上表中的關鍵字建立查詢,以識別匹配文件並對其進行更新。實際的更新操作由方法本身的 @Update 註解定義,如下面的列表所示。請注意,派生查詢的命名方案以 find 開頭。使用 update(如 updateAllByLastname(…​))僅在與 @Query 結合使用時才允許。

更新應用於 所有 匹配文件,並且 不可能 透過傳入 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)
}
1 更新的過濾器查詢從方法名派生。更新是“按原樣”執行的,不繫結任何引數。
2 實際的增量值由繫結到 ?1 佔位符的 increment 方法引數定義。
3 使用 Spring 表示式語言 (SpEL) 進行引數繫結。
4 使用 pipeline 屬性發出 聚合管道更新
5 更新可能包含複雜物件。
6 基於字串的查詢 與更新結合起來。
倉庫更新不發出持久化或對映生命週期事件。

刪除方法

上表中的關鍵字可以與 delete…Byremove…By 結合使用,以建立刪除匹配文件的查詢。

Delete…By 查詢
  • 命令式

  • 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)
}
1 使用 List 返回型別會在實際刪除所有匹配文件之前檢索並返回它們。
2 數字返回型別直接刪除匹配文件,並返回刪除的文件總數。
3 單個領域型別結果檢索並刪除第一個匹配文件。
4 與 3 相同,但包裝在 Optional 型別中。
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)
}
1 使用 Flux 返回型別會在實際刪除所有匹配文件之前檢索並返回它們。
2 數字返回型別直接刪除匹配文件,並返回刪除的文件總數。
3 單個領域型別結果檢索並刪除第一個匹配文件。
© . This site is unofficial and not affiliated with VMware.