简体   繁体   English

MongoDB:查询和返回嵌入式文档列表

[英]MongoDB: Query For and Return List of Embedded Documents

I have several solutions , which in term may hold several projects . 我有几个solutions ,可以solutions多个projects I modeled this relationship by embedding the projects in the solution document, eg 我通过embedding项目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"
      }
    ]
 }]

Now I want to select all projects of a special type, eg Java . 现在,我想select all projects特殊类型的select all projects ,例如Java I tried the following query with aggregation: 我用聚合尝试了以下query

db.Solutions.aggregate ( 
    { "$unwind": "$projects" }, 
    { "$match": {"projects.type": "Java" } }, 
    { "$project": {"projects" : 1, "_id": 0, "solutionTitle": 0 } } 
)

This works fine but the result doesn't look like what I expected. 这工作正常,但结果与我预期的不一样。 I get 我懂了

{
    projects: {
        _id: "12",
        type: "Java",
        title: "Test Project"
    },
    projects: {
        _id: "21",
        type: "Java",
        title: "Another Java Project"
    }
}

How can I get the result to be a list of projects, eg 我如何获得结果作为项目列表,例如

[
    { _id: "12", type: "Java", title: "Test Project" }
    ...
]

I checked this SO question and this one , but they do not really cover what I need. 我检查了这个SO问题这个 问题 ,但是它们并没有真正满足我的需求。 Any help is greatly appreciated. 任何帮助是极大的赞赏。

If you want them to be in an array, you'll need to add them to an array: 如果希望它们位于数组中,则需要将它们添加到数组中:

db.Solutions.aggregate ([
    { "$unwind": "$projects" }, 
    { "$match": {"projects.type": "Java" } }, 
    { "$group": {"_id": null, "projects": { "$push": "$projects" } } }
])

In light of your comments below, it seems what you really want is to return the project subdocuments as if they were the documents you were searching. 根据下面的评论,您似乎真正想要的是返回项目子文档,就像它们是您正在搜索的文档一样。 In which case you should $project your project values explicitly: 在这种情况下,您应该$project明确显示项目值:

db.Solutions.aggregate ([
    { "$unwind": "$projects" }, 
    { "$match": {"projects.type": "Java" } }, 
    { "$project": {"_id": "$projects._id", "type": "$projects.type", "title": "$projects.title" } }
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM