Mongodb 在聚合查询中仅显示某些嵌套字段
我有一个聚合查询:Mongodb 在聚合查询中仅显示某些嵌套字段,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我有一个聚合查询: db.laureates.aggregate([ { $match : { "nobelPrizes.affiliations.name.en" : "CERN" }}, { $project : { _id: 0, "nobelPrizes.affiliations.country.en" : 1 }}, { $limit : 1}]).pretty() 其结果是: { "nobelPr
db.laureates.aggregate([
{ $match : { "nobelPrizes.affiliations.name.en" : "CERN" }},
{ $project : { _id: 0, "nobelPrizes.affiliations.country.en" : 1 }},
{ $limit : 1}]).pretty()
其结果是:
{
"nobelPrizes" : [
{
"affiliations" : [
{
"country" : {
"en" : "Switzerland"
}
}
]
}
]
}
查询的结果值是正确的(瑞士),但我试图只打印结果中的某些字段,即country。应该是这样的:
{ "country" : "Switzerland" }
如何排除“国家”字段旁边的字段?我知道聚合管道的投影部分可以排除与目标平行的字段,但是如何才能对嵌套字段执行此操作?您可以使用
$unwind
展开数组
db.collection.aggregate([
{ "$unwind": "$nobelPrizes"},
{ "$unwind": "$nobelPrizes.affiliations"},
{ $match: { "nobelPrizes.affiliations.country.en": "Switzerland"}},
{
$project: {
_id: 0,
"country": "$nobelPrizes.affiliations.country.en"
}
},
{ $limit: 1 }
])
工作