【发布时间】:2022-10-21 13:59:32
【问题描述】:
给定具有以下结构的文档:
{
"_id": "XXXX01",
"otherAttributes", "....",
"child": [{
"_id": "YYYY01",
"otherAttributes", "....",
"grandChild": [{
"_id": "ZZZZ01",
"otherAttributes", "...."
}]
}]
}
使用原始 mongo 方言,可以实现以下目标:
插入根
db.collection.findAndModify({
query: { "_id": "XXXX01" },
update: {
"_id": "XXXX01",
"otherAttributes", "....",
"child": [{
"_id": "YYYY01",
"otherAttributes", "....",
"grandChild": [{
"_id": "ZZZZ01",
"otherAttributes", "...."
}]
}]
},
upsert: true
})
但是类似的 findAndReplace 与 mongoTemplate 例如。
var document = new Document();
mongoTemplate.getConverter().write(javaObjectRepresentingTheDocument, document);
update = Update.fromDocument(document) // Primary because I dont want to set each field individually
query.addCriteria(
Criteria.where("id").is("XXXX01")
);
mongoTemplate.findAndModify(query, update,
FindAndModifyOptions.options().upsert(true).returnNew(true),
javaObjectRepresentingTheDocument.getClass(),
collection
)
导致以下错误:
Caused by: java.lang.IllegalArgumentException: Invalid BSON field name _id
at org.bson.AbstractBsonWriter.writeName(AbstractBsonWriter.java:534) ~[bson-4.4.3.jar:na]
...
我想使用findAndReplace 而不是upsert 的原因是:
- 我需要当前对象
- 概括代码即。相同的方法(
findAndReplace)对于所有级别的插入和更新都很有用,即。根文档,嵌套文档,例如。child,一个深度嵌套的文档,例如。grandChild我已经成功通过使用
child和grandChild嵌套文档获得相同的工作update.addToSet("$[parentSelector]", javaObjectRepresentingTheNestedDocument) .filterArray(Criteria.where("parentSelector._id").is(<parentSelectorValue>))但无法为根文档获得相同的工作。有人可以提供一些指导吗?
【问题讨论】:
标签: java spring mongodb spring-data spring-data-mongodb