我在 MacOS Sierra 10.12.2中使用 mongodb 3.4.0
我的收藏如下:
{
"_id" : ObjectId("58837a559caf2fc968adc64d"),
"box_location" : [
{
"country" : "Taiwan",
"country_code" : "TW",
"location" : [
{
"city" : "Taipei",
"name" : "Taipei 101"
}
]
},
{
"country" : "Hong Kong",
"country_code" : "HK",
"location" : [
{
"city" : "Hong Kong",
"name" : "Hung Hom Station"
}
]
}
]
}
我使用了以下查询
db.setting.findOne({"box_location.country_code":"TW"}, {box_location:1, _id:0})
db.setting.find({"box_location.country_code":"TW"}, {box_location:1, _id:0})
db.setting.find({
"box_location": {
$elemMatch :{
"country_code":"TW"
}
}
})
并始终返回 box_location 中的所有文档,而不只是 TW 国家/地区代码中的 box_location 。
我一直在搜索解决方案,它总是提到点符号或 elemMatch ,但它们都不起作用
当我查询国家代码TW时,它应该只返回
"box_location" : [
{
"country" : "Taiwan",
"country_code" : "TW",
"location" : [
{
"city" : "Taipei",
"name" : "Taipei 101"
}
]
}
]
答案 0 :(得分:0)
好的,
db.setting.aggregate(
{$unwind: "$box_location"},
{$match: {"box_location.country_code": "TW"}}
)
结帐文档https://docs.mongodb.com/v3.2/reference/operator/aggregation/unwind/
答案 1 :(得分:0)
您可以在$elemMatch
find()
db.settings.find({
"box_location.country_code":"TW"
},
{
_id : 0,
box_location : {
$elemMatch : {
country_code : "TW"
}
}
})