如何在 MongoDB 查找查询中获取投影中的嵌套对象?
[
{
"apikey": 1,
"meta": {
"region": {
"country": "India",
"city": "bangalore",
"pincode": 560067
},
"address": {
"houseNo": "G/C 42 Whitefield boulavourd",
"landmark": "whitefield boulavourd"
}
}
},
{
"apikey": 2,
"meta": {
"region": {
"country": "Germaany",
"city": "Munich",
"pincode": 80297
},
"address": {
"houseNo": "Zweibrückenstraße 12",
"landmark": "Zweibrückenstraße 12"
}
}
}
]
我试图获取
apikey: "2"
的区域。我尝试了以下查找查询:
db.collection.find({
"apikey": "2"
},
{
"projection": {
"_id": 0,
"apikey": 1,
"meta.region": 1
}
})
我收到一个错误,因为无法将字段
meta.region
包含在排除投影中。
还有其他方法可以解决这个问题吗?
我想要输出:
[
{
"apikey":2,
"region": {
"country": "Germaany",
"city": "Munich",
"pincode": 80297
}
}
]
删除
projection
(环绕)级别。
db.collection.find({
apikey: 2
},
{
"_id": 1,
"apikey": "$apikey",
"region": "$meta.region"
})