保存、更新和删除文档
MongoTemplate / ReactiveMongoTemplatge允许您保存、更新和删除域对象,并将这些对象映射到存储在 MongoDB 中的文档。
命令式 API 和反应式 API 的 API 签名基本相同,只是返回类型不同。
虽然同步 API 使用void单Object和List反应式对应物包括Mono<Void>,Mono<Object>和Flux.
请考虑以下类:
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 + "]";
}
}
鉴于Person类,您可以保存、更新和删除对象,如下例所示:
-
Imperative
-
Reactive
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):
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导致String以及一个ObjectId通过识别(通过约定)存储在数据库中的Idproperty name 属性。
前面的示例旨在演示如何对MongoTemplate / ReactiveMongoTemplate而不是显示复杂的映射功能。
前面示例中使用的查询语法在 “查询文档” 一节中有更详细的说明。
MongoDB 要求您有一个_id字段。请参阅 ID 处理部分,了解有关此字段的特殊处理的详细信息。 |
| MongoDB 集合可以包含表示各种类型实例的文档。有关详细信息,请参阅类型映射。 |
插入 / 保存
有几种方便的方法MongoTemplate用于保存和插入对象。
要对转换过程进行更精细的控制,可以使用MappingMongoConverter— 例如Converter<Person, Document>和Converter<Document, Person>.
| 插入作和保存作之间的区别在于,如果对象尚不存在,则保存作将执行插入。 |
使用 save作的简单情况是保存一个 POJO。 在这种情况下,集合名称由类的名称(非完全限定)确定。 您还可以使用特定的集合名称调用 save作。您可以使用映射元数据覆盖用于存储对象的集合。
插入或保存时,如果Id属性,则假设其值将由数据库自动生成。
因此,为了自动生成ObjectId要成功,需要Idproperty 或 field 必须是String一ObjectId或BigInteger.
以下示例显示如何保存文档并检索其内容:
-
Imperative
-
Reactive
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());
可以使用以下 insert 和 save作:
-
void救(Object objectToSave):将对象保存到默认集合。 -
void救(Object objectToSave, String collectionName):将对象保存到指定的集合中。
也可以使用一组类似的 insert作:
-
void插入(Object objectToSave):将对象插入到默认集合中。 -
void插入(Object objectToSave, String collectionName):将对象插入到指定的集合中。
如何_idField 在 Mapping Layer 中处理
MongoDB 要求您有一个_id字段。
如果您不提供,驱动程序会分配一个ObjectId替换为生成的值,而不考虑您的域模型,因为服务器不知道您的标识符类型。
当您使用MappingMongoConverter中,某些规则控制 Java 类中的属性如何映射到 this_id田:
-
带有
@Id(org.springframework.data.annotation.Id) 映射到_id田。 -
没有注释但名为
id映射到_id田。
下面概述了对映射到_iddocument 字段(使用MappingMongoConverter(默认值MongoTemplate).
-
如果可能,请使用
id声明为String转换为 Java 类并存储为ObjectId通过使用 SpringConverter<String, ObjectId>.有效的转换规则将委托给 MongoDB Java 驱动程序。如果无法转换为ObjectId,则该值将作为字符串存储在数据库中。 -
一
id声明为BigInteger转换为 Java 类并存储为ObjectId通过使用 SpringConverter<BigInteger, ObjectId>.
如果 Java 类中不存在前几组规则中指定的字段或属性,则隐式的_idfile 由驱动程序生成,但未映射到 Java 类的属性或字段。
在查询和更新时,MongoTemplate使用与上述规则对应的转换器来保存文档,以便查询中使用的字段名称和类型可以匹配域类中的内容。
某些环境需要自定义的映射方法Id值,例如存储在 MongoDB 中的数据,这些数据未通过 Spring Data 映射层运行。文档可以包含_id值,可以表示为ObjectId或String.
将文档从存储读取回域类型工作正常。通过其id可能由于隐式的ObjectId转换。因此,无法以这种方式检索文档。
对于这些情况@MongoId提供对实际 ID 映射尝试的更多控制。
@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 的 API API 中,否则为String.对应于@Id用法。 |
我的文档将保存到哪个集合中?
有两种方法可以管理用于文档的集合名称。
使用的默认集合名称是更改为以小写字母开头的类名。
所以一个com.test.Person类存储在person收集。
您可以通过在@Document注解。
您还可以通过提供自己的集合名称作为所选MongoTemplate方法调用。
插入或保存单个对象
MongoDB 驱动程序支持在单个作中插入文档集合。
以下方法在MongoOperationsinterface 支持此功能:
-
insert:插入对象。如果存在具有相同
id,则生成错误。 -
insertAll:采用
Collectionof objects 作为第一个参数。此方法根据前面指定的规则检查每个对象并将其插入到相应的集合中。 -
save:保存对象,覆盖可能具有相同
id.
在批处理中插入多个对象
MongoDB 驱动程序支持在一个作中插入文档集合。
以下方法在MongoOperations接口通过以下方式支持此功能insert或专用的BulkOperations接口。
-
Imperative
-
Reactive
Collection<Person> inserted = template.insert(List.of(...), Person.class);
Flux<Person> inserted = template.insert(List.of(...), Person.class);
-
Imperative
-
Reactive
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();
|
批处理和批量的服务器性能相同。 但是,批量作不会发布生命周期事件。 |
|
任何 |
更新
对于更新,您可以使用MongoOperation.updateFirst或者,您可以使用MongoOperation.updateMultimethod 或all在 Fluent API 上。
以下示例显示了所有SAVINGS我们将使用$inc算子:
MongoTemplate / ReactiveMongoTemplate-
Imperative
-
Reactive
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 的更新修饰符匹配的方法。
大多数方法都会返回Updateobject 为 API 提供 Fluent 样式。
|
|
运行文档更新的方法
-
updateFirst:使用更新的文档更新与查询文档条件匹配的第一个文档。
-
updateMulti:使用更新的文档更新与查询文档条件匹配的所有对象。
updateFirst不支持排序。请使用 findAndModify 申请Sort. |
更新作的索引提示可以通过以下方式提供Query.withHint(…). |
Methods 中的Update类
你可以用一点 “'syntax sugar'” 和Updateclass 的 API 中,因为它的方法应该链接在一起。
此外,您可以启动创建新的Update实例public static Update update(String key, Object value)以及使用静态导入。
这Updateclass 包含以下方法:
-
UpdateaddToSet(String key, Object value)使用 Update using the update$addToSet更新修饰符 -
Update当前日期(String key)使用 Update using the update$currentDate更新修饰符 -
Update当前时间戳(String key)使用 Update using the update$currentDateupdate 修饰符替换为$typetimestamp -
Update公司(String key, Number inc)使用 Update using the update$inc更新修饰符 -
Update麦克斯(String key, Object max)使用 Update using the update$max更新修饰符 -
Update分钟(String key, Object min)使用 Update using the update$min更新修饰符 -
Update乘(String key, Number multiplier)使用 Update using the update$mul更新修饰符 -
Update流行(String key, Update.Position pos)使用 Update using the update$pop更新修饰符 -
Update拉(String key, Object value)使用 Update using the update$pull更新修饰符 -
Update拉全部(String key, Object[] values)使用 Update using the update$pullAll更新修饰符 -
Update推(String key, Object value)使用 Update using the update$push更新修饰符 -
Update全部(String key, Object[] values)使用 Update using the update$pushAll更新修饰符 -
Update重命名(String oldName, String newName)使用 Update using the update$rename更新修饰符 -
Update设置(String key, Object value)使用 Update using the update$set更新修饰符 -
UpdatesetOnInsert(String key, Object value)使用 Update using the update$setOnInsert更新修饰符 -
Update未凝固的(String key)使用 Update using the update$unset更新修饰符
某些更新修饰符(例如$push和$addToSet,允许嵌套其他运算符。
// { $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");
聚合管道更新
Update 方法公开MongoOperations和ReactiveMongoOperations也通过AggregationUpdate.
用AggregationUpdate允许在更新作中利用 MongoDB 4.2 聚合。
在更新中使用聚合允许通过使用单个作表示多个阶段和多个条件来更新一个或多个字段。
更新可以包括以下阶段:
-
AggregationUpdate.set(…).toValue(…)→$set : { … } -
AggregationUpdate.unset(…)→$unset : [ … ] -
AggregationUpdate.replaceWith(…)→$replaceWith : { … }
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 | 第一$setstage 根据 tests 字段的平均值计算新的字段平均值。 |
| 2 | 第 2 个$set阶段根据第一个聚合阶段计算的平均字段计算新的字段等级。 |
| 3 | 该管道在 students 集合上运行,并使用Student对于聚合字段映射。 |
| 4 | 将更新应用于集合中的所有匹配文档。 |
Upsert
与执行updateFirst作中,您还可以执行upsert作,如果未找到与查询匹配的文档,则将执行 INSERT。
插入的文档是 query 文档和 update 文档的组合。
以下示例演示如何使用upsert方法:
-
Imperative
-
Reactive
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. |
|
|
替换集合中的文档
各种replace方法可通过MongoTemplateallow 覆盖第一个匹配的 Document。
如果未找到匹配项,则可以更新插入新的匹配项(如上一节所述),方法是提供ReplaceOptions与根据配置。
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作为 existing 或 no_id完全。 |
| 4 | 运行 replace作。 .将一个替换为 upsert |
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 | 这_id值,否则 MongoDB 将创建一个新的 Potentially 域类型不兼容ObjectId.
由于 MongoDB 无法识别您的域类型,因此任何@Field(targetType)提示,生成的ObjectId可能与您的域模型不兼容。 |
| 2 | 用upsert如果未找到匹配项,则插入新文档 |
|
无法更改 |
查找和修改
这findAndModify(…)method 开启MongoCollection可以更新文档,并在单个作中返回旧文档或新更新的文档。MongoTemplate提供四个findAndModify采用Query和Update类并转换自Document到你的 POJOs:
<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操作:
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,upsert和remove.
从前面的代码片段扩展的示例如下:
Person upserted = template.update(Person.class)
.matching(new Query(Criteria.where("firstName").is("Mary")))
.apply(update)
.withOptions(FindAndModifyOptions.options().upsert(true).returnNew(true))
.findAndModifyValue()
|
|
查找和替换
替换整个Document通过其id使用save方法。
但是,这可能并不总是可行的。findAndReplace提供了一种替代方法,允许通过简单的查询来标识要替换的文档。
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,fields和collation设置。 |
| 3 | 额外的可选钩子来提供默认值以外的选项,例如upsert. |
| 4 | 用于映射作结果的可选投影类型。如果没有,则使用初始域类型。 |
| 5 | 触发实际处理。用findAndReplaceValue获取可为 null 的结果,而不是Optional. |
请注意,更换件不得持有id本身作为id的现有Document将是
由商店本身结转到替代品。还要记住findAndReplace将仅替换第一个
document 匹配查询条件,具体取决于可能给定的排序顺序。 |
删除
您可以使用以下五种重载方法之一从数据库中删除对象:
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,limit和skip选项,然后在单独的步骤中一次性删除所有选项。 |
| 4 | 从GOT收集。与 <3> 不同,文档不会批量删除,而是逐个删除。 |
| 5 | 删除GOT收集。与 <3> 不同,文档不会批量删除,而是逐个删除。 |
乐观锁定
这@Versionannotation 提供的语法类似于 MongoDB 上下文中的 JPA 语法,并确保更新仅应用于具有匹配版本的文档。
因此,将 version 属性的实际值添加到 update 查询中,如果另一个作同时更改了文档,则 update 不会产生任何影响。
在这种情况下,一个OptimisticLockingFailureException被抛出。
以下示例显示了这些功能:
@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和 bumpversion自1. |
| 4 | 尝试更新之前加载的文档,该文档仍然具有version = 0.作失败,并显示OptimisticLockingFailureException,作为当前version是1. |
仅对MongoTemplate请考虑并更改版本属性。请咨询MongoOperationsJava doc 了解详细信息。
Optimistic Locking 需要设置WriteConcern自ACKNOWLEDGED.否则OptimisticLockingFailureException可以静默吞咽。 |
从版本 2.2 开始MongoOperations还包括@Version属性。
要删除Document无需进行版本检查,请使用MongoOperations#remove(Query,…)而不是MongoOperations#remove(Object). |
从版本 2.2 开始,存储库在删除版本控制实体时检查确认删除的结果。
一OptimisticLockingFailureException如果无法通过CrudRepository.delete(Object).在这种情况下,版本已更改或同时删除了对象。用CrudRepository.deleteById(ID)绕过乐观锁定功能并删除对象,无论其版本如何。 |