对于最新的稳定版本,请使用 Spring Data MongoDB 4.4.0! |
保存、更新和删除文档
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
通过识别(通过约定)存储在数据库中的Id
property name 属性。
前面的示例旨在演示如何对MongoTemplate
/ ReactiveMongoTemplate
而不是显示复杂的映射功能。
前面示例中使用的查询语法在 “查询文档” 一节中有更详细的说明。
MongoDB 要求您有一个_id 字段。请参阅 ID 处理部分,了解有关此字段的特殊处理的详细信息。 |
MongoDB 集合可以包含表示各种类型实例的文档。有关详细信息,请参阅类型映射。 |
插入 / 保存
有几种方便的方法MongoTemplate
用于保存和插入对象。
要对转换过程进行更精细的控制,可以使用MappingMongoConverter
— 例如Converter<Person, Document>
和Converter<Document, Person>
.
插入作和保存作之间的区别在于,如果对象尚不存在,则保存作将执行插入。 |
使用 save作的简单情况是保存一个 POJO。 在这种情况下,集合名称由类的名称(非完全限定)确定。 您还可以使用特定的集合名称调用 save作。您可以使用映射元数据覆盖用于存储对象的集合。
插入或保存时,如果Id
属性,则假设其值将由数据库自动生成。
因此,为了自动生成ObjectId
要成功,需要Id
property 或 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)
:将对象插入到指定的集合中。
如何_id
Field 在 Mapping Layer 中处理
MongoDB 要求您有一个_id
字段。
如果您不提供,驱动程序会分配一个ObjectId
替换为生成的值,而不考虑您的域模型,因为服务器不知道您的标识符类型。
当您使用MappingMongoConverter
中,某些规则控制 Java 类中的属性如何映射到 this_id
田:
-
带有
@Id
(org.springframework.data.annotation.Id
) 映射到_id
田。 -
没有注释但名为
id
映射到_id
田。
下面概述了对映射到_id
document 字段(使用MappingMongoConverter
(默认值MongoTemplate
).
-
如果可能,请使用
id
声明为String
转换为 Java 类并存储为ObjectId
通过使用 SpringConverter<String, ObjectId>
.有效的转换规则将委托给 MongoDB Java 驱动程序。如果无法转换为ObjectId
,则该值将作为字符串存储在数据库中。 -
一
id
声明为BigInteger
转换为 Java 类并存储为ObjectId
通过使用 SpringConverter<BigInteger, ObjectId>
.
如果 Java 类中不存在前几组规则中指定的字段或属性,则隐式的_id
file 由驱动程序生成,但未映射到 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 的 API API 中,否则为String .对应于@Id 用法。 |
我的文档将保存到哪个集合中?
有两种方法可以管理用于文档的集合名称。
使用的默认集合名称是更改为以小写字母开头的类名。
所以一个com.test.Person
类存储在person
收集。
您可以通过在@Document
注解。
您还可以通过提供自己的集合名称作为所选MongoTemplate
方法调用。
插入或保存单个对象
MongoDB 驱动程序支持在单个作中插入文档集合。
以下方法在MongoOperations
interface 支持此功能:
-
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
在 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
对象。
这Update
class 具有与可用于 MongoDB 的更新修饰符匹配的方法。
大多数方法都会返回Update
object 为 API 提供 Fluent 样式。
|
运行文档更新的方法
-
updateFirst:使用更新的文档更新与查询文档条件匹配的第一个文档。
-
updateMulti:使用更新的文档更新与查询文档条件匹配的所有对象。
updateFirst 不支持排序。请使用 findAndModify 申请Sort . |
更新作的索引提示可以通过以下方式提供Query.withHint(…) . |
Methods 中的Update
类
你可以用一点 “'syntax sugar'” 和Update
class 的 API 中,因为它的方法应该链接在一起。
此外,您可以启动创建新的Update
实例public static Update update(String key, Object value)
以及使用静态导入。
这Update
class 包含以下方法:
-
Update
addToSet(String key, Object value)
使用 Update using the update$addToSet
更新修饰符 -
Update
当前日期(String key)
使用 Update using the update$currentDate
更新修饰符 -
Update
当前时间戳(String key)
使用 Update using the update$currentDate
update 修饰符替换为$type
timestamp
-
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
更新修饰符 -
Update
setOnInsert(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 | 第一$set stage 根据 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
方法可通过MongoTemplate
allow 覆盖第一个匹配的 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
这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 | 用于映射作结果的可选投影类型。如果没有,则使用初始域类型。 |
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> 不同,文档不会批量删除,而是逐个删除。 |
乐观锁定
这@Version
annotation 提供的语法类似于 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
请考虑并更改版本属性。请咨询MongoOperations
Java 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) 绕过乐观锁定功能并删除对象,无论其版本如何。 |