保存、更新和删除文档
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
class 中,可以保存、更新和删除对象,如以下示例所示:
-
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
通过识别(通过约定)将Id
属性名称。
前面的示例旨在演示对MongoTemplate
/ ReactiveMongoTemplate
并且不显示复杂的映射功能。
“查询文档”一节更详细地介绍了前面示例中使用的查询语法。
MongoDB 要求您有一个_id 字段。有关此字段的特殊处理的详细信息,请参阅身份证件处理部分。 |
MongoDB 集合可以包含表示各种类型实例的文档。详情请参考类型映射。 |
插入/保存
有几种方便的方法MongoTemplate
用于保存和插入您的对象。
为了对转换过程进行更细粒度的控制,您可以使用MappingMongoConverter
——例如Converter<Person, Document>
和Converter<Document, Person>
.
插入作和保存作之间的区别在于,如果对象尚不存在,则保存作将执行插入。 |
使用保存作的简单情况是保存一个 POJO。 在这种情况下,集合名称由类的名称(非完全限定)确定。 您还可以使用特定的集合名称调用保存作。可以使用映射元数据来替代要存储对象的集合。
插入或保存时,如果Id
属性未设置,则假设其值将由数据库自动生成。
因此,对于自动生成的ObjectId
要成功,则Id
属性或字段必须是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());
以下插入和保存作可用:
-
void
救(Object objectToSave)
:将对象保存到默认集合。 -
void
救(Object objectToSave, String collectionName)
:将对象保存到指定的集合。
还提供了一组类似的插入作:
-
void
插入(Object objectToSave)
:将对象插入到默认集合。 -
void
插入(Object objectToSave, String collectionName)
:将对象插入到指定的集合中。
如何_id
在映射图层中处理字段
MongoDB 要求您有一个_id
字段。
如果您不提供,驱动程序会分配一个ObjectId
使用生成的值,而不考虑您的域模型,因为服务器不知道您的标识符类型。
当您使用MappingMongoConverter
,某些规则控制 Java 类中的属性如何映射到_id
田:
-
用
@Id
(org.springframework.data.annotation.Id
) 映射到_id
田。 -
没有注释但名为
id
映射到_id
田。
下面概述了在映射到_id
文档字段时使用MappingMongoConverter
(默认值MongoTemplate
).
-
如果可能,请
id
属性或字段声明为String
在 Java 类中被转换为并存储为ObjectId
通过使用 SpringConverter<String, ObjectId>
.有效的转换规则被委托给MongoDB Java驱动程序。如果无法将其转换为ObjectId
,则该值将作为字符串存储在数据库中。 -
一
id
属性或字段声明为BigInteger
在 Java 类中被转换为并存储为ObjectId
通过使用 SpringConverter<BigInteger, ObjectId>
.
如果 Java 类中不存在前面的规则集中指定的字段或属性,则隐式的_id
文件由驱动程序生成,但未映射到 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 是有效的ObjectId hex,否则为String .对应于@Id 用法。 |
我的文档保存到哪个集合中?
有两种方法可以管理用于文档的集合名称。
使用的默认集合名称是更改为以小写字母开头的类名。
所以一个com.test.Person
类存储在person
收集。 您可以通过提供不同的集合名称来自定义此作,并带有@Document
注解。 您还可以通过提供自己的集合名称作为所选MongoTemplate
方法调用。
插入或保存单个对象
MongoDB 驱动程序支持在单个作中插入文档集合。以下方法MongoOperations
接口支持此功能:
-
insert:插入对象。如果存在具有相同
id
,则生成错误。 -
insertAll:采用
Collection
of 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.updateMulti
method 或all
在流畅的 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
对象。
这Update
class 具有与 MongoDB 可用的更新修饰符匹配的方法。
大多数方法返回Update
对象为 API 提供流畅的样式。
|
运行文档更新的方法
-
updateFirst:使用更新的文档更新与查询文档条件匹配的第一个文档。
-
updateMulti:使用更新的文档更新与查询文档条件匹配的所有对象。
updateFirst 不支持对 8.0 以下版本的 MongoDB 进行订购。运行旧版本之一,请使用 findAndModify 申请Sort . |
更新作的索引提示可以通过以下方式提供Query.withHint(…) . |
Methods 中的Update
类
你可以在Update
类,因为它的方法旨在链接在一起。
此外,您还可以启动创建新的Update
实例,使用public static Update update(String key, Object value)
以及使用静态导入。
这Update
class 包含以下方法:
-
Update
addToSet(String key, Object value)
使用$addToSet
更新修饰符 -
Update
当前日期(String key)
使用$currentDate
更新修饰符 -
Update
当前时间戳(String key)
使用$currentDate
update 修饰符$type
timestamp
-
Update
公司(String key, Number inc)
使用$inc
更新修饰符 -
Update
麦克斯(String key, Object max)
使用$max
更新修饰符 -
Update
分钟(String key, Object min)
使用$min
更新修饰符 -
Update
乘(String key, Number multiplier)
使用$mul
更新修饰符 -
Update
流行(String key, Update.Position pos)
使用$pop
更新修饰符 -
Update
拉(String key, Object value)
使用$pull
更新修饰符 -
Update
拉全部(String key, Object[] values)
使用$pullAll
更新修饰符 -
Update
推(String key, Object value)
使用$push
更新修饰符 -
Update
推全部(String key, Object[] values)
使用$pushAll
更新修饰符 -
Update
重命名(String oldName, String newName)
使用$rename
更新修饰符 -
Update
设置(String key, Object value)
使用$set
更新修饰符 -
Update
setOnInsert(String key, Object value)
使用$setOnInsert
更新修饰符 -
Update
未凝固的(String key)
使用$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");
聚合管道更新
更新方法公开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 | 第1个$set 阶段根据测试字段的平均值计算新的字段平均值。 |
2 | 第2届$set 阶段根据第一个聚合阶段计算的平均字段计算新的字段等级。 |
3 | 管道在 students 集合上运行,并使用Student 用于聚合字段映射。 |
4 | 将更新应用于集合中的所有匹配文档。 |
更新插入
与执行updateFirst
作,您还可以执行upsert
作,如果找不到与查询匹配的文档,则将执行插入。
插入的文档是查询文档和更新文档的组合。
以下示例演示如何使用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
可通过以下方式获得的方法MongoTemplate
允许覆盖第一个匹配的文档。
如果没有找到匹配项,则可以通过提供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 作为现有或没有_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 | 这_id upsert 需要存在值,否则 MongoDB 将创建一个具有域类型不兼容的新可能ObjectId .
由于 MongoDB 不知道您的域类型,因此任何@Field(targetType) 不考虑提示,生成的ObjectId 可能与您的域模型不兼容。 |
2 | 用upsert 如果未找到匹配项,则插入新文档 |
无法更改 |
查找和修改
这findAndModify(…)
方法MongoCollection
可以在单个作中更新文档并返回旧文档或新更新文档。MongoTemplate
提供四个findAndModify
重载的方法Query
和Update
类和转换Document
到你的 POJO:
<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
这FindAndModifyOptions
method 允许您设置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 | 用于映射作结果的可选投影类型。如果给定 none,则使用初始域类型。 |
5 | 触发实际处理。用findAndReplaceValue 以获取可为 null 的结果,而不是Optional . |
请注意,替换件不得装有id 本身作为id 现有的Document 将是
由商店本身进行更换。还要记住findAndReplace 只会替换第一个
与查询条件匹配的文档,具体取决于可能给定的排序顺序。 |
删除
可以使用五种重载方法之一从数据库中删除对象:
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> 不同,文档不会批量删除,而是逐个删除。 |
乐观锁定
这@Version
注释提供类似于 MongoDB 上下文中的 JPA 语法,并确保更新仅应用于具有匹配版本的文档。
因此,version 属性的实际值将添加到更新查询中,以便在另一个作同时更改文档时更新不会产生任何影响。
在这种情况下,一个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 和颠簸version 自1 . |
4 | 尝试更新之前加载的文档,该文档仍然有version = 0 .该作失败,并显示OptimisticLockingFailureException ,作为当前version 是1 . |
仅对某些 CRUD作MongoTemplate
请考虑和更改版本属性。请咨询MongoOperations
Java 文档以获取详细信息。
Optimistic Locking 需要将WriteConcern 自ACKNOWLEDGED .否则OptimisticLockingFailureException 可以默默地咽下去。 |
从 2.2 版开始MongoOperations 还包括@Version 属性。
要删除Document 不使用 version checkMongoOperations#remove(Query,…) 而不是MongoOperations#remove(Object) . |
从版本 2.2 开始,存储库在删除版本化实体时检查已确认删除的结果。
一OptimisticLockingFailureException 如果无法通过CrudRepository.delete(Object) .在这种情况下,版本已更改或对象被删除。用CrudRepository.deleteById(ID) 绕过乐观锁定功能并删除对象,无论其版本如何。 |