【发布时间】:2016-12-18 03:13:40
【问题描述】:
我正在尝试使用 Spring Data MongoDB 更新 mongodb 中嵌入文档中的数组字段。
我想在 mongodb 集合中更新/插入的文档结构如下。
根据每个部门的类型,可以有更多这样的文档,比如“销售”、“营销”等等。
{
"timestamp": "2014-09-26T04:00:00.000Z",
"department": "accounts",
"employee": [
{
"type": "regular",
"names": [
"Raj",
"Kumar",
"Shankar"
]
},
{
"type": "contract",
"names": [
"Penny",
"Sheldon",
"bob"
]
},
{
"type": "temp",
"names": [
"jerry",
"kramer",
"bubbleboy"
]
}
]
}
基本上,我的更新查询如下,
db.getCollection('mytest').update(
{
"timestamp" : "2014-09-26T04:00:00.000Z",
"department" : "accounts",
"employee.type" : "regular"
},
{ $addToSet: { "employee.$.names" : "Jo" } },
{
upsert: true
}
)
我添加了 upsert: true ,因为如果没有与查询匹配的文档,我想将该文档插入到 mytest 集合中。
当我从 mongo shell 执行相同的操作时,我收到以下错误。
The positional operator did not find the match needed from the query. Unexpanded update: employee.$.names
即使这样可行,我不确定我们是否有类似的支持来在 Spring Data mongodb 中实现相同的功能。
另外,我的另一个查询是,如果我想为多个部门添加/更新员工,比如“帐户”和“销售”,看来我必须使用不同的值执行相同的查询作为数量我想相应地更新部门(如果不存在则插入)。
是否有更好更高效的选项,例如批量/批量,我可以在单个 mongo 更新查询中同时更新/插入多个部门的员工。另外,spring data mongodb/mongotemplate 中是否有相同的支持。
【问题讨论】:
-
您是否有机会查看以下解决方案,看看它是否解决了您的问题?
标签: mongodb spring-data-mongodb bson mongotemplate