MongoDB - 根据条件从数组返回匹配的子文档

时间:2016-02-01 08:03:11

标签: mongodb

想象一下如下文档 -

我想和PART一起返回 输入将是语言“ENG”或“FRA”或“GER”

文献 -

{
    "_id" : ObjectId("56a5337f19d312a4156a3625"),
    "PartId" : "Part1",
    "Name" : "Name",
    "active" : "true",
    "attribute1" : "value1",
    "attribute2" : "value2",
    "LanguageData":[ 
        {
            "Language" : "ENG",
            "description" : "PARt1- English",
            "default" : "true"
        }, 
        {
            "Language" : "FRA",
            "description" : "Part1 in french",
            "supported" : "true"
        }, 
        {
            "Language" : "GER",
            "description" : "Part1 In German",
            "supported" : "false"
        }
    ]
}

如果输入为“ENG”

{
    "_id" : ObjectId("56a5337f19d312a4156a3625"),
    "PartId" : "Part1",
    "Name" : "Name",
    "active" : "true",
    "attribute1" : "value1",
    "attribute2" : "value2",
    "LanguageData":[ 
        {
            "Language" : "ENG",
            "description" : "PARt1- English",
            "default" : "true"
        }
    ]
}

如果输入为“GER”,则输出不应将此文档作为“支持为假”

返回
{}

如果输入为“CHN”,则应返回默认值 -

{
    "_id" : ObjectId("56a5337f19d312a4156a3625"),
    "PartId" : "Part1",
    "Name" : "Name",
    "active" : "true",
    "attribute1" : "value1",
    "attribute2" : "value2",
    "LanguageData":[ 
        {
            "Language" : "ENG",
            "description" : "PARt1- English",
            "default" : "true"
        }
    ]
}

我无法根据条件返回子文档

只应根据以下条件返回数组中的子文档

1)因此,如果存在语言,则返回该子文档。

2)如果Sub-Document不存在,则始终返回默认值。

3)如果Sub Document存在且不受支持,请不要返回整个文档

1 个答案:

答案 0 :(得分:2)

要查询子文档,可以通过aggregate

执行此操作
db.document.aggregate([
    {$match: {'LanguageData.Language': 'GER'}},
    {$project: {
        LanguageData: {$filter: {
            input: '$LanguageData',
            as: 'LanguageData',
            cond: {$eq: ['$$LanguageData.Language', 'GER']}
        }}
    }}
])

要返回默认数据,$ifNull可以执行该操作

db.document.aggregate([
    {$unwind: '$LanguageData'}, 
    {$match: {'LanguageData.Language': 'GER'}}, 
    {$project: 
       {LanguageData: 
          {Language: {$ifNull: ['$LanguageData.Language', 'CHN']}, 
           description: {$ifNull: ['$LanguageData.description', 'default description']}}}}
]);