Mongodb';s$match返回同一文档的多个匹配项
我的文件结构如下:Mongodb';s$match返回同一文档的多个匹配项,mongodb,mongodb-query,database,Mongodb,Mongodb Query,Database,我的文件结构如下: { name: "some user name", cvs: [{ title: 'Cv title' technologies: [ { text: 'JavaScript', main: true }, { text: "AngularJs", main: true } ] }] } 当我进行以下聚合时(db中只有一个文档):
{
name: "some user name",
cvs: [{
title: 'Cv title'
technologies: [
{
text: 'JavaScript',
main: true
},
{
text: "AngularJs",
main: true
}
]
}]
}
当我进行以下聚合时(db中只有一个文档):
我得到一个包含两个元素的数组(但这是同一个文档),因为有两种技术匹配
"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"],
}
]
运行以下管道,将附加的和管道步骤放入其中,以聚合管道(将管道放置在之前,以过滤通过管道的不需要的文档)获得所需的结果(使用操作符按给定字段对文档进行分组,使用累加器创建数组):
这就是诀窍!但是结果中缺少了“类型”和“熟练程度”。只有标题和技术是正确的there@user2814599更新的答案,错别字。现在应该可以了:-)我应该在问之前检查一下以找到错别字!。它起作用了!谢谢您能否告诉我,我如何将“用户”集合本身(具有上述嵌套文档)中的数据包含到$project中?例如user.name.您能为这个问题创建一个新的问题吗?请显示与您收藏的文档结构相同的示例文档。我认为有更好的方法来做到这一点。
[
{
"_id" : ObjectId("5629e813279b62fe075fbd4c"),
"type" : "Frontend",
"proficiency" : "Middle",
"title" : "Frontend developer",
"technologies" : ["JavaScript", "Ruby"],
}
]
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,
}
}
])