保存、更新和删除文档

MongoTemplate / ReactiveMongoTemplatge允许您保存、更新和删除域对象,并将这些对象映射到存储在MongoDB中的文档。 命令式 API 和响应式 API 的 API 签名主要相同,只是返回类型不同。 虽然同步 API 使用voidObjectList反应性对应物包括Mono<Void>,Mono<Object>Flux.spring-doc.cadn.net.cn

考虑以下类:spring-doc.cadn.net.cn

public class Person {

	private String id;
	private String name;
	private int age;

	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public int getAge() {
		return age;
	}

	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
}

鉴于Personclass 中,可以保存、更新和删除对象,如以下示例所示:spring-doc.cadn.net.cn

public class MongoApplication {

  private static final Log log = LogFactory.getLog(MongoApplication.class);

  public static void main(String[] args) {

    MongoOperations template = new MongoTemplate(new SimpleMongoClientDbFactory(MongoClients.create(), "database"));

    Person p = new Person("Joe", 34);

    // Insert is used to initially store the object into the database.
    template.insert(p);
    log.info("Insert: " + p);

    // Find
    p = template.findById(p.getId(), Person.class);
    log.info("Found: " + p);

    // Update
    template.updateFirst(query(where("name").is("Joe")), update("age", 35), Person.class);
    p = template.findOne(query(where("name").is("Joe")), Person.class);
    log.info("Updated: " + p);

    // Delete
    template.remove(p);

    // Check that deletion worked
    List<Person> people =  template.findAll(Person.class);
    log.info("Number of people = : " + people.size());


    template.dropCollection(Person.class);
  }
}

前面的示例将生成以下日志输出(包括来自MongoTemplate):spring-doc.cadn.net.cn

DEBUG apping.MongoPersistentEntityIndexCreator:  80 - Analyzing class class org.spring.example.Person for index information.
DEBUG work.data.mongodb.core.MongoTemplate: 632 - insert Document containing fields: [_class, age, name] in collection: person
INFO               org.spring.example.MongoApp:  30 - Insert: Person [id=4ddc6e784ce5b1eba3ceaf5c, name=Joe, age=34]
DEBUG work.data.mongodb.core.MongoTemplate:1246 - findOne using query: { "_id" : { "$oid" : "4ddc6e784ce5b1eba3ceaf5c"}} in db.collection: database.person
INFO               org.spring.example.MongoApp:  34 - Found: Person [id=4ddc6e784ce5b1eba3ceaf5c, name=Joe, age=34]
DEBUG work.data.mongodb.core.MongoTemplate: 778 - calling update using query: { "name" : "Joe"} and update: { "$set" : { "age" : 35}} in collection: person
DEBUG work.data.mongodb.core.MongoTemplate:1246 - findOne using query: { "name" : "Joe"} in db.collection: database.person
INFO               org.spring.example.MongoApp:  39 - Updated: Person [id=4ddc6e784ce5b1eba3ceaf5c, name=Joe, age=35]
DEBUG work.data.mongodb.core.MongoTemplate: 823 - remove using query: { "id" : "4ddc6e784ce5b1eba3ceaf5c"} in collection: person
INFO               org.spring.example.MongoApp:  46 - Number of people = : 0
DEBUG work.data.mongodb.core.MongoTemplate: 376 - Dropped collection [database.person]
public class ReactiveMongoApplication {

  private static final Logger log = LoggerFactory.getLogger(ReactiveMongoApplication.class);

  public static void main(String[] args) throws Exception {

    CountDownLatch latch = new CountDownLatch(1);

    ReactiveMongoTemplate template = new ReactiveMongoTemplate(MongoClients.create(), "database");

    template.insert(new Person("Joe", 34)).doOnNext(person -> log.info("Insert: " + person))
      .flatMap(person -> template.findById(person.getId(), Person.class))
      .doOnNext(person -> log.info("Found: " + person))
      .zipWith(person -> template.updateFirst(query(where("name").is("Joe")), update("age", 35), Person.class))
      .flatMap(tuple -> template.remove(tuple.getT1())).flatMap(deleteResult -> template.findAll(Person.class))
      .count().doOnSuccess(count -> {
        log.info("Number of people: " + count);
        latch.countDown();
      })

      .subscribe();

    latch.await();
  }
}

MongoConverter导致StringObjectId通过识别(通过约定)将Id属性名称。spring-doc.cadn.net.cn

前面的示例旨在演示对MongoTemplate / ReactiveMongoTemplate并且不显示复杂的映射功能。 “查询文档”一节更详细地介绍了前面示例中使用的查询语法。spring-doc.cadn.net.cn

MongoDB 要求您有一个_id字段。有关此字段的特殊处理的详细信息,请参阅身份证件处理部分。
MongoDB 集合可以包含表示各种类型实例的文档。详情请参考类型映射

插入/保存

有几种方便的方法MongoTemplate用于保存和插入您的对象。 为了对转换过程进行更细粒度的控制,您可以使用MappingMongoConverter——例如Converter<Person, Document>Converter<Document, Person>.spring-doc.cadn.net.cn

插入作和保存作之间的区别在于,如果对象尚不存在,则保存作将执行插入。

使用保存作的简单情况是保存一个 POJO。 在这种情况下,集合名称由类的名称(非完全限定)确定。 您还可以使用特定的集合名称调用保存作。可以使用映射元数据来替代要存储对象的集合。spring-doc.cadn.net.cn

插入或保存时,如果Id属性未设置,则假设其值将由数据库自动生成。 因此,对于自动生成的ObjectId要成功,则Id属性或字段必须是StringObjectIdBigInteger.spring-doc.cadn.net.cn

以下示例显示如何保存文档并检索其内容:spring-doc.cadn.net.cn

使用 MongoTemplate 插入和检索文档
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Criteria.query;

//...

template.insert(new Person("Bob", 33));

Person person = template.query(Person.class)
    .matching(query(where("age").is(33)))
    .oneValue();
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Criteria.query;

//...

Mono<Person> person = mongoTemplate.insert(new Person("Bob", 33))
    .then(mongoTemplate.query(Person.class)
        .matching(query(where("age").is(33)))
        .one());

以下插入和保存作可用:spring-doc.cadn.net.cn

还提供了一组类似的插入作:spring-doc.cadn.net.cn

如何_id在映射图层中处理字段

MongoDB 要求您有一个_id字段。 如果您不提供,驱动程序会分配一个ObjectId使用生成的值,而不考虑您的域模型,因为服务器不知道您的标识符类型。 当您使用MappingMongoConverter,某些规则控制 Java 类中的属性如何映射到_id田:spring-doc.cadn.net.cn

  1. @Id (org.springframework.data.annotation.Id) 映射到_id田。spring-doc.cadn.net.cn

  2. 没有注释但名为id映射到_id田。spring-doc.cadn.net.cn

下面概述了在映射到_id文档字段时使用MappingMongoConverter(默认值MongoTemplate).spring-doc.cadn.net.cn

  1. 如果可能,请id属性或字段声明为String在 Java 类中被转换为并存储为ObjectId通过使用 SpringConverter<String, ObjectId>.有效的转换规则被委托给MongoDB Java驱动程序。如果无法将其转换为ObjectId,则该值将作为字符串存储在数据库中。spring-doc.cadn.net.cn

  2. id属性或字段声明为BigInteger在 Java 类中被转换为并存储为ObjectId通过使用 SpringConverter<BigInteger, ObjectId>.spring-doc.cadn.net.cn

如果 Java 类中不存在前面的规则集中指定的字段或属性,则隐式的_id文件由驱动程序生成,但未映射到 Java 类的属性或字段。spring-doc.cadn.net.cn

查询和更新时,MongoTemplate使用与上述规则相对应的转换器来保存文档,以便查询中使用的字段名称和类型可以与域类中的字段名称和类型匹配。spring-doc.cadn.net.cn

某些环境需要自定义方法来绘制地图Id值,例如存储在MongoDB中未通过Spring Data映射层运行的数据。文档可以包含_id可以表示为ObjectId或作为String. 将文档从存储中读回域类型可以正常工作。通过其id由于隐式ObjectId转换。因此,无法以这种方式检索文档。 对于这些情况@MongoId提供对实际 ID 映射尝试的更多控制。spring-doc.cadn.net.cn

示例 1.@MongoId映射
public class PlainStringId {
  @MongoId String id; (1)
}

public class PlainObjectId {
  @MongoId ObjectId id; (2)
}

public class StringToObjectId {
  @MongoId(FieldType.OBJECT_ID) String id; (3)
}
1 id 被视为String无需进一步转换。
2 id 被视为ObjectId.
3 id 被视为ObjectId如果给定的String是有效的ObjectIdhex,否则为String.对应于@Id用法。

我的文档保存到哪个集合中?

有两种方法可以管理用于文档的集合名称。 使用的默认集合名称是更改为以小写字母开头的类名。 所以一个com.test.Person类存储在person收集。 您可以通过提供不同的集合名称来自定义此作,并带有@Document注解。 您还可以通过提供自己的集合名称作为所选MongoTemplate方法调用。spring-doc.cadn.net.cn

插入或保存单个对象

MongoDB 驱动程序支持在单个作中插入文档集合。以下方法MongoOperations接口支持此功能:spring-doc.cadn.net.cn

  • insert:插入对象。如果存在具有相同id,则生成错误。spring-doc.cadn.net.cn

  • insertAll:采用Collectionof objects 作为第一个参数。此方法检查每个对象,并根据前面指定的规则将其插入到适当的集合中。spring-doc.cadn.net.cn

  • save:保存对象,覆盖任何可能具有相同id.spring-doc.cadn.net.cn

在批处理中插入多个对象

MongoDB 驱动程序支持在一次作中插入文档集合。 以下方法MongoOperations接口通过以下方式支持此功能insert或专用的BulkOperations接口。spring-doc.cadn.net.cn

批次插入
Collection<Person> inserted = template.insert(List.of(...), Person.class);
Flux<Person> inserted = template.insert(List.of(...), Person.class);
散装插入
BulkWriteResult result = template.bulkOps(BulkMode.ORDERED, Person.class)
    .insert(List.of(...))
    .execute();
Mono<BulkWriteResult> result = template.bulkOps(BulkMode.ORDERED, Person.class)
    .insert(List.of(...))
    .execute();

批处理和批量的服务器性能相同。 但是,批量作不会发布生命周期事件spring-doc.cadn.net.cn

任何@Version在调用 insert 之前尚未设置的属性将自动初始化1(如果是简单的类型,例如int) 或0对于包装器类型(例如Integer).
在参见乐观锁定部分阅读更多内容。
spring-doc.cadn.net.cn

更新

对于更新,您可以使用MongoOperation.updateFirst或者,您可以使用MongoOperation.updateMultimethod 或all在流畅的 API 上。 以下示例显示了所有SAVINGS我们将使用$inc算子:spring-doc.cadn.net.cn

使用MongoTemplate / ReactiveMongoTemplate
import static org.springframework.data.mongodb.core.query.Criteria.where;
import org.springframework.data.mongodb.core.query.Update;

// ...

UpdateResult result = template.update(Account.class)
    .matching(where("accounts.accountType").is(Type.SAVINGS))
    .apply(new Update().inc("accounts.$.balance", 50.00))
    .all();
import static org.springframework.data.mongodb.core.query.Criteria.where;
import org.springframework.data.mongodb.core.query.Update;

// ...

Mono<UpdateResult> result = template.update(Account.class)
    .matching(where("accounts.accountType").is(Type.SAVINGS))
    .apply(new Update().inc("accounts.$.balance", 50.00))
    .all();

除了Query前面讨论过,我们通过使用Update对象。 这Updateclass 具有与 MongoDB 可用的更新修饰符匹配的方法。 大多数方法返回Update对象为 API 提供流畅的样式。spring-doc.cadn.net.cn

@Version属性,如果未包含在Update将自动递增。 在参见乐观锁定部分阅读更多内容。spring-doc.cadn.net.cn

运行文档更新的方法

  • updateFirst:使用更新的文档更新与查询文档条件匹配的第一个文档。spring-doc.cadn.net.cn

  • updateMulti:使用更新的文档更新与查询文档条件匹配的所有对象。spring-doc.cadn.net.cn

updateFirst不支持对 8.0 以下版本的 MongoDB 进行订购。运行旧版本之一,请使用 findAndModify 申请Sort.
更新作的索引提示可以通过以下方式提供Query.withHint(…​).

Methods 中的Update

你可以在Update类,因为它的方法旨在链接在一起。 此外,您还可以启动创建新的Update实例,使用public static Update update(String key, Object value)以及使用静态导入。spring-doc.cadn.net.cn

Updateclass 包含以下方法:spring-doc.cadn.net.cn

一些更新修饰符,例如$push$addToSet,允许嵌套其他运算符。spring-doc.cadn.net.cn

// { $push : { "category" : { "$each" : [ "spring" , "data" ] } } }
new Update().push("category").each("spring", "data")

// { $push : { "key" : { "$position" : 0 , "$each" : [ "Arya" , "Arry" , "Weasel" ] } } }
new Update().push("key").atPosition(Position.FIRST).each(Arrays.asList("Arya", "Arry", "Weasel"));

// { $push : { "key" : { "$slice" : 5 , "$each" : [ "Arya" , "Arry" , "Weasel" ] } } }
new Update().push("key").slice(5).each(Arrays.asList("Arya", "Arry", "Weasel"));

// { $addToSet : { "values" : { "$each" : [ "spring" , "data" , "mongodb" ] } } }
new Update().addToSet("values").each("spring", "data", "mongodb");

聚合管道更新

更新方法公开MongoOperationsReactiveMongoOperations也接受聚合管道AggregationUpdate. 用AggregationUpdate允许在更新作中利用 MongoDB 4.2 聚合。 在更新中使用聚合允许通过使用单个作表示多个阶段和多个条件来更新一个或多个字段。spring-doc.cadn.net.cn

更新可以包括以下阶段:spring-doc.cadn.net.cn

示例 2.更新聚合
AggregationUpdate update = Aggregation.newUpdate()
    .set("average").toValue(ArithmeticOperators.valueOf("tests").avg())     (1)
    .set("grade").toValue(ConditionalOperators.switchCases(                 (2)
        when(valueOf("average").greaterThanEqualToValue(90)).then("A"),
        when(valueOf("average").greaterThanEqualToValue(80)).then("B"),
        when(valueOf("average").greaterThanEqualToValue(70)).then("C"),
        when(valueOf("average").greaterThanEqualToValue(60)).then("D"))
        .defaultTo("F")
    );

template.update(Student.class)                                              (3)
    .apply(update)
    .all();                                                                 (4)
db.students.update(                                                         (3)
   { },
   [
     { $set: { average : { $avg: "$tests" } } },                            (1)
     { $set: { grade: { $switch: {                                          (2)
                           branches: [
                               { case: { $gte: [ "$average", 90 ] }, then: "A" },
                               { case: { $gte: [ "$average", 80 ] }, then: "B" },
                               { case: { $gte: [ "$average", 70 ] }, then: "C" },
                               { case: { $gte: [ "$average", 60 ] }, then: "D" }
                           ],
                           default: "F"
     } } } }
   ],
   { multi: true }                                                          (4)
)
1 第1个$set阶段根据测试字段的平均值计算新的字段平均值
2 第2届$set阶段根据第一个聚合阶段计算的平均字段计算新的字段等级
3 管道在 students 集合上运行,并使用Student用于聚合字段映射。
4 将更新应用于集合中的所有匹配文档。

更新插入

与执行updateFirst作,您还可以执行upsert作,如果找不到与查询匹配的文档,则将执行插入。 插入的文档是查询文档和更新文档的组合。 以下示例演示如何使用upsert方法:spring-doc.cadn.net.cn

UpdateResult result = template.update(Person.class)
  .matching(query(where("ssn").is(1111).and("firstName").is("Joe").and("Fraizer").is("Update"))
  .apply(update("address", addr))
  .upsert();
Mono<UpdateResult> result = template.update(Person.class)
  .matching(query(where("ssn").is(1111).and("firstName").is("Joe").and("Fraizer").is("Update"))
  .apply(update("address", addr))
  .upsert();
upsert不支持订购。请使用 findAndModify 进行申请Sort.

@Version属性,如果未包含在Update将自动初始化。 在参见乐观锁定部分阅读更多内容。spring-doc.cadn.net.cn

替换集合中的文档

各种replace可通过以下方式获得的方法MongoTemplate允许覆盖第一个匹配的文档。 如果没有找到匹配项,则可以通过提供ReplaceOptions具有相应的配置。spring-doc.cadn.net.cn

更换一个
Person tom = template.insert(new Person("Motte", 21)); (1)
Query query = Query.query(Criteria.where("firstName").is(tom.getFirstName())); (2)
tom.setFirstname("Tom"); (3)
template.replace(query, tom, ReplaceOptions.none()); (4)
1 插入新文档。
2 用于标识要替换的单个文档的查询。
3 设置必须包含相同_id作为现有或没有_id完全。
4 运行替换作。 .用更新插入替换一个
Person tom = new Person("id-123", "Tom", 21) (1)
Query query = Query.query(Criteria.where("firstName").is(tom.getFirstName()));
template.replace(query, tom, ReplaceOptions.replaceOptions().upsert()); (2)
1 _idupsert 需要存在值,否则 MongoDB 将创建一个具有域类型不兼容的新可能ObjectId. 由于 MongoDB 不知道您的域类型,因此任何@Field(targetType)不考虑提示,生成的ObjectId可能与您的域模型不兼容。
2 upsert如果未找到匹配项,则插入新文档

无法更改_id具有替换作的现有文档。 上upsertMongoDB 使用 2 种方法来确定条目的新 ID: *这_id在查询中使用,如{"_id" : 1234 }*这_id存在于替换文档中。 如果没有_id无论以哪种方式提供,MongoDB 都会创建一个新的ObjectId对于文档。 如果使用的域类型,这可能会导致映射和数据查找故障idproperty 具有不同的类型,例如Long.spring-doc.cadn.net.cn

查找和修改

findAndModify(…)方法MongoCollection可以在单个作中更新文档并返回旧文档或新更新文档。MongoTemplate提供四个findAndModify重载的方法QueryUpdate类和转换Document到你的 POJO:spring-doc.cadn.net.cn

<T> T findAndModify(Query query, Update update, Class<T> entityClass);

<T> T findAndModify(Query query, Update update, Class<T> entityClass, String collectionName);

<T> T findAndModify(Query query, Update update, FindAndModifyOptions options, Class<T> entityClass);

<T> T findAndModify(Query query, Update update, FindAndModifyOptions options, Class<T> entityClass, String collectionName);

以下示例插入一些Person对象放入容器中,并执行findAndUpdate操作:spring-doc.cadn.net.cn

template.insert(new Person("Tom", 21));
template.insert(new Person("Dick", 22));
template.insert(new Person("Harry", 23));

Query query = new Query(Criteria.where("firstName").is("Harry"));
Update update = new Update().inc("age", 1);

Person oldValue = template.update(Person.class)
  .matching(query)
  .apply(update)
  .findAndModifyValue(); // oldValue.age == 23

Person newValue = template.query(Person.class)
  .matching(query)
  .findOneValue(); // newValye.age == 24

Person newestValue = template.update(Person.class)
  .matching(query)
  .apply(update)
  .withOptions(FindAndModifyOptions.options().returnNew(true)) // Now return the newly updated document when updating
  .findAndModifyValue(); // newestValue.age == 25

FindAndModifyOptionsmethod 允许您设置returnNew,upsertremove. 下面是从前面的代码片段扩展的示例:spring-doc.cadn.net.cn

Person upserted = template.update(Person.class)
  .matching(new Query(Criteria.where("firstName").is("Mary")))
  .apply(update)
  .withOptions(FindAndModifyOptions.options().upsert(true).returnNew(true))
  .findAndModifyValue()

@Version属性,如果未包含在Update将自动递增。 在参见乐观锁定部分阅读更多内容。spring-doc.cadn.net.cn

查找和替换

替换整个的最直接方法Document是通过其id使用save方法。 然而,这可能并不总是可行的。findAndReplace提供了一种替代方案,允许通过简单的查询来识别要替换的文档。spring-doc.cadn.net.cn

示例 3.查找和替换文档
Optional<User> result = template.update(Person.class)      (1)
    .matching(query(where("firstame").is("Tom")))          (2)
    .replaceWith(new Person("Dick"))
    .withOptions(FindAndReplaceOptions.options().upsert()) (3)
    .as(User.class)                                        (4)
    .findAndReplace();                                     (5)
1 将 fluent update API 与给定的域类型一起使用,用于映射查询和派生集合名称,或者仅使用MongoOperations#findAndReplace.
2 映射到给定域类型的实际匹配查询。提供sort,fieldscollation设置。
3 额外的可选钩子,用于提供默认值以外的选项,例如upsert.
4 用于映射作结果的可选投影类型。如果给定 none,则使用初始域类型。
5 触发实际处理。用findAndReplaceValue以获取可为 null 的结果,而不是Optional.
请注意,替换件不得装有id本身作为id现有的Document将是 由商店本身进行更换。还要记住findAndReplace只会替换第一个 与查询条件匹配的文档,具体取决于可能给定的排序顺序。

删除

可以使用五种重载方法之一从数据库中删除对象:spring-doc.cadn.net.cn

template.remove(tywin, "GOT");                                              (1)

template.remove(query(where("lastname").is("lannister")), "GOT");           (2)

template.remove(new Query().limit(3), "GOT");                               (3)

template.findAllAndRemove(query(where("lastname").is("lannister"), "GOT");  (4)

template.findAllAndRemove(new Query().limit(3), "GOT");                     (5)
1 删除由其指定的单个实体_id从关联的集合中。
2 GOT收集。
3 删除GOT收集。与 <2> 不同,要删除的文档由其_id,运行给定的查询,应用sort,limitskip选项,然后在单独的步骤中一次性删除所有选项。
4 GOT收集。与 <3> 不同,文档不会批量删除,而是逐个删除。
5 删除GOT收集。与 <3> 不同,文档不会批量删除,而是逐个删除。

乐观锁定

@Version注释提供类似于 MongoDB 上下文中的 JPA 语法,并确保更新仅应用于具有匹配版本的文档。 因此,version 属性的实际值将添加到更新查询中,以便在另一个作同时更改文档时更新不会产生任何影响。 在这种情况下,一个OptimisticLockingFailureException被抛出。 以下示例显示了这些功能:spring-doc.cadn.net.cn

@Document
class Person {

  @Id String id;
  String firstname;
  String lastname;
  @Version Long version;
}

Person daenerys = template.insert(new Person("Daenerys"));                            (1)

Person tmp = template.findOne(query(where("id").is(daenerys.getId())), Person.class); (2)

daenerys.setLastname("Targaryen");
template.save(daenerys);                                                              (3)

template.save(tmp); // throws OptimisticLockingFailureException                       (4)
1 初始插入文档。version设置为0.
2 加载刚刚插入的文档。version还是0.
3 使用version = 0.将lastname和颠簸version1.
4 尝试更新之前加载的文档,该文档仍然有version = 0.该作失败,并显示OptimisticLockingFailureException,作为当前version1.

仅对某些 CRUD作MongoTemplate请考虑和更改版本属性。请咨询MongoOperationsJava 文档以获取详细信息。spring-doc.cadn.net.cn

Optimistic Locking 需要将WriteConcernACKNOWLEDGED.否则OptimisticLockingFailureException可以默默地咽下去。
从 2.2 版开始MongoOperations还包括@Version属性。 要删除Document不使用 version checkMongoOperations#remove(Query,…​)而不是MongoOperations#remove(Object).
从版本 2.2 开始,存储库在删除版本化实体时检查已确认删除的结果。 一OptimisticLockingFailureException如果无法通过CrudRepository.delete(Object).在这种情况下,版本已更改或对象被删除。用CrudRepository.deleteById(ID)绕过乐观锁定功能并删除对象,无论其版本如何。