带子阵列的Mongo投影滤镜

时间:2019-03-26 20:50:16

标签: mongodb projection

{
"_id" : "000f7ef7-b4d2-4b3a-a33a-ce4f5a6dc594",
"ClientCode" : "67018",
"ClientName" : "test06",    
"Addresses" : [ 
    {            
        "AddressTypeCode" : "1",             
        "EmailAddress" : "test1@gmail.com"
    }, 
    {            
        "AddressTypeCode" : "2",                         
        "EmailAddress" : "test2@gmail.com"
    }
    , 
    {            
        "AddressTypeCode" : "3",            
        "EmailAddress" : "test3@gmail.com"
    }
]

}

我想使用mongo投影获得以下结果,该过滤条件为AddressTypeCode等于1的子数组Address的过滤条件,并获取电子邮件地址。

{  "ClientCode" : "67018",  "ClientName" : "test06",  "EmailAddress" :test1@gmail.com"}

1 个答案:

答案 0 :(得分:0)

我首先要放松一下:

{ $unwind : "$Addresses" }

然后进行比赛:

{ $match : { "Addresses.AddressTypeCode" : "1" } }

然后进行投影:

{ $project : { "ClientCode" : 1, "ClientName" : 1, "EmailAddress" : "$Addresses.AddressTypeCode" } }