我有几个solutions
,其中可以容纳多个projects
。我通过embedding
解决方案文档中的项目来建模这种关系,例如
[{
_id: "1",
solutionTitle: "Some Test Solution",
projects: [
{
_id: "12",
type: "Java",
title: "Test Project"
},
{
_id: "13",
type: "Misc",
title: "Test Project"
}
]
},
{
_id: "2",
solutionTitle: "A Different Solution",
projects: [
{
_id: "21",
type: "Java",
title: "Another Java Project"
}
]
}]
现在我想select all projects
特殊类型,例如Java
。我使用聚合尝试了以下query
:
db.Solutions.aggregate (
{ "$unwind": "$projects" },
{ "$match": {"projects.type": "Java" } },
{ "$project": {"projects" : 1, "_id": 0, "solutionTitle": 0 } }
)
这很好但结果看起来不像我的预期。我得到了
{
projects: {
_id: "12",
type: "Java",
title: "Test Project"
},
projects: {
_id: "21",
type: "Java",
title: "Another Java Project"
}
}
如何将结果作为项目列表,例如
[
{ _id: "12", type: "Java", title: "Test Project" }
...
]
我检查了this SO question和this one,但它们并没有真正涵盖我需要的内容。非常感谢任何帮助。
答案 0 :(得分:1)
如果您希望它们位于数组中,则需要将它们添加到数组中:
db.Solutions.aggregate ([
{ "$unwind": "$projects" },
{ "$match": {"projects.type": "Java" } },
{ "$group": {"_id": null, "projects": { "$push": "$projects" } } }
])
根据您在下面的评论,您真正想要的是返回项目子文档,就好像它们是您正在搜索的文档一样。在这种情况下,您应明确$project
您的项目值:
db.Solutions.aggregate ([
{ "$unwind": "$projects" },
{ "$match": {"projects.type": "Java" } },
{ "$project": {"_id": "$projects._id", "type": "$projects.type", "title": "$projects.title" } }
])