MongoDB使用匹配和投影展开空数组 - 返回所有父项

时间:2015-04-09 16:19:07

标签: mongodb mongodb-query

我正在尝试过滤子文档以返回符合特定条件的文档,在这种情况下,返回首选手机。如果没有匹配,请返回父级并清空首选电话。这是我目前的模特:

[{
    "_id": 1,
    "FirstName": "Elaine",
    "LastName": "Benes",
    "Phones": [{
        "PhoneNumber": "(123)123-1234",
        "PhoneTypeId": 1,
        "IsPreferred": true
    },{
        "PhoneNumber": "(321)321-4321",
        "PhoneTypeId": 2,
        "IsPreferred": false
    }]
},{
    "_id": 2,
    "FirstName": "Jerry",
    "LastName": "Seinfeld",
    "Phones": [{
        "PhoneNumber": "(123)123-1234",
        "PhoneTypeId": 1,
        "IsPreferred": true
    }]
},{
    "_id": 3,
    "FirstName": "Cosmo",
    "LastName": "Kramer",
    "Phones": [{
        "PhoneNumber": "(123)123-1234",
        "PhoneTypeId": 1,
        "IsPreferred": false
    }]
},{
    "_id": 4,
    "FirstName": "George",
    "LastName": "Costanza",
    "Phones": []
}]

我想回复以下内容:

[{
    "_id": 1,
    "FirstName": "Elaine",
    "LastName": "Benes",
    "PreferredPhone": {
        "PhoneNumber": "(123)123-1234",
        "PhoneTypeId": 1,
        "IsPreferred": true
    }
},{
    "_id": 2,
    "FirstName": "Jerry",
    "LastName": "Seinfeld",
    "PreferredPhone": {
        "PhoneNumber": "(123)123-1234",
        "PhoneTypeId": 1,
        "IsPreferred": true
    }
},{
    "_id": 3,
    "FirstName": "Cosmo",
    "LastName": "Kramer",
    "PreferredPhone": null
},{
    "_id": 4,
    "FirstName": "George",
    "LastName": "Costanza",
    "PreferredPhone": null
}]

我尝试使用聚合来展开并进行匹配然后投影,如下所示:

{
    "$unwind": "$Phones"
},
{
    "$match": {
        "IsPreferred": true
    }
},
{
    "$project": {
        "FirstName": "$FirstName",
        "LastName": "$LastName",
        "PreferredPhone" : { 
            "PhoneNumber" : "$Phones.PhoneNumber", 
            "PhoneTypeId" : "$Phones.PhoneTypeId", 
            "PhoneId" : "$Phones.PhoneId" 
        }   
    }
}

我也尝试过类似于这个问题中提出的建议: Unwind empty array in mongodb

我只想获得前两个文件,因为我真的希望所有这些文件都有首选手机或空数组。这可能吗?

1 个答案:

答案 0 :(得分:1)

MongoDB 2.2的新的$ elemMatch投影运算符提供了另一种方法来改变返回的文档,使其只包含第一个匹配的形状元素:

db.test.find(
     {}, 
     {'FirstName':1,'LastName':1,Phones: {$elemMatch: {'IsPreferred': true}}}
);

返回:

[{
    "_id" : 1,
    "FirstName" : "Elaine",
    "LastName" : "Benes",
    "Phones" : [ 
        {
            "PhoneNumber" : "(123)123-1234",
            "PhoneTypeId" : 1,
            "IsPreferred" : true
        }
    ]
}
{
    "_id" : 2,
    "FirstName" : "Jerry",
    "LastName" : "Seinfeld",
    "Phones" : [ 
        {
            "PhoneNumber" : "(123)123-1234",
            "PhoneTypeId" : 1,
            "IsPreferred" : true
        }
    ]
}
{
    "_id" : 3,
    "FirstName" : "Cosmo",
    "LastName" : "Kramer"
}
{
    "_id" : 4,
    "FirstName" : "George",
    "LastName" : "Costanza"
}]

虽然该领域"手机"仍然是一个数组。