我有以下文档结构:
{
name: "some user name",
cvs: [{
title: 'Cv title'
technologies: [
{
text: 'JavaScript',
main: true
},
{
text: "AngularJs",
main: true
}
]
}]
}
当我进行以下聚合时(db中只有一个文档):
db.users.aggregate([
{"$unwind": "$cvs"},
{"$unwind": "$cvs.technologies"},
{"$match": {
"cvs.isBlocked": false,
"cvs.moderated": true,
"cvs.isVisible": true,
"cvs.technologies.main": true
}
},
{"$project": {
"type": "$cvs.occupationType",
"proficiency": "$cvs.proficiencyLevel",
"_id": "$cvs._id",
"title": "$cvs.title",
"technologies": "$cvs.technologies.text",
}}
])
我得到了两个元素的数组(但这是同一个文档),因为有两种技术匹配
"cvs.technologies.main": true
[
{
"_id" : ObjectId("5629e813279b62fe075fbd4c"),
"type" : "Frontend",
"proficiency" : "Middle",
"title" : "Frontend developer",
"technologies" : "JavaScript",
},
{
"_id" : ObjectId("5629e813279b62fe075fbd4c"),
"type" : "Frontend",
"proficiency" : "Middle",
"title" : "Frontend developer",
"technologies" : "Ruby",
}
]
我怎样才能得到这个结果?:
[
{
"_id" : ObjectId("5629e813279b62fe075fbd4c"),
"type" : "Frontend",
"proficiency" : "Middle",
"title" : "Frontend developer",
"technologies" : ["JavaScript", "Ruby"],
}
]
答案 0 :(得分:1)
运行以下管道,其中包含额外的 $match
和 $group
管道步骤,以便 optimize 汇总管道(在 $match
之前放置一个 $unwind
管道,以过滤掉通过管道的不需要的文件)获得所需的结果(使用 $group
运算符按给定字段对文档进行分组,使用 $push
累加器创建数组):
db.users.aggregate([
{
"$match": {
"cvs.isBlocked": false,
"cvs.moderated": true,
"cvs.isVisible": true,
"cvs.technologies.main": true
}
},
{"$unwind": "$cvs"},
{"$unwind": "$cvs.technologies"},
{
"$match": {
"cvs.isBlocked": false,
"cvs.moderated": true,
"cvs.isVisible": true,
"cvs.technologies.main": true
}
},
{
"$group": {
"_id": {
"type": "$cvs.occupationType",
"proficiency": "$cvs.proficiencyLevel",
"_id": "$cvs._id",
"title": "$cvs.title"
},
"technologies": {
"$push": "$cvs.technologies.text"
}
}
},
{
"$project": {
"type": "$_id.type",
"proficiency": "$_id.proficiency",
"_id": "$_id._id",
"title": "$_id.title",
"technologies": 1,
}
}
])