MongoDB-基于其当前内容的更新嵌套文档
我有一个简单的收藏品,其中包含这样的文档:
{
_id: ObjectId('62b196e43581370007773393'),
name: 'John',
jobs: [
{
company: 'ACME',
type: 'programmer',
technologies: [
{
level: 1,
name: 'Java'
},
{
level: 3,
name: 'MongoDB'
}
]
}
]
}
我想将所有技术收集到“求职者”作业的“作业”子文件中的新领域,以实现这一效果:
(...)
jobs: [
{
it_technologies : ["Java", "MongoDB"]
(...)
}
]
(...)
问题是我确实做到了 。不知道如何使用此查询来参考文档的适当元素:
db.runCommand({update: "employees",
updates: [
{
q: {},
u: { $set: { "jobs.$[j].it_technologies": "<how to collect all technologies in this job?>" } },
upsert: false,
multi: true,
arrayFilters: [{
$and:
[
{"j.type": "programmer"},
{"j.technologies": {$exists : true, $ne: []} }
]
}]
}
] });
完全有可能吗? 我很感激任何线索!
I have a simple collection with a document like this one:
{
_id: ObjectId('62b196e43581370007773393'),
name: 'John',
jobs: [
{
company: 'ACME',
type: 'programmer',
technologies: [
{
level: 1,
name: 'Java'
},
{
level: 3,
name: 'MongoDB'
}
]
}
]
}
I'd like to collect all technologies into a new field in the "job" sub-document for "programmers" jobs only, to achieve this effect:
(...)
jobs: [
{
it_technologies : ["Java", "MongoDB"]
(...)
}
]
(...)
The problem is that I do not know how to refer to and collect proper elements of the documents with this query:
db.runCommand({update: "employees",
updates: [
{
q: {},
u: { $set: { "jobs.$[j].it_technologies": "<how to collect all technologies in this job?>" } },
upsert: false,
multi: true,
arrayFilters: [{
$and:
[
{"j.type": "programmer"},
{"j.technologies": {$exists : true, $ne: []} }
]
}]
}
] });
Is it at all possible?
I'd be grateful for any clue!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
认为您需要使用聚合管道来进行更新。
地图
- 用作业数组返回并返回新数组。
1.1。
和$ cond
- 检查条件(匹配作业的当前文档
type技术
不是一个空数组) 。如果满足,则更新文档,否则仍然存在。1.1.1。
$ MergeObjects
- 将当前文档与it_technologies
合并。示例mongo playground
Think that you need to work the update with the aggregation pipeline.
map
- Iterate with thejobs
array and return a new array.1.1.
$cond
- Check the condition (Match the current document ofjobs
type
andtechnology
is not an empty array). If fulfilled, then update the document, else remains existing.1.1.1.
$mergeObjects
- Merge current document with the document withit_technologies
.Sample Mongo Playground