我是MongoDB
的新手。我在MongoDB中有以下集合。我的问题是我无法根据提供的ID或名称创建一个提供所需设施的查找命令。
查找我尝试过但不工作的命令: -
db.mgh_facilities.find({facilities: {$elemMatch: {name: "Foreign exchange assistance"}}}).
对我而言,它返回所有记录。不应该只是返回{“id”:“11”,“name”:“外汇援助”}
我的收藏: -
{
"_id" : ObjectId("548acc28ae6ff1c0fd1d7470"),
"responseCode" : "true",
"facilities" : [
{
"id" : "11",
"name" : "Foreign exchange assistance"
},
{
"id" : "12",
"name" : "Assistance with luggage on request"
},
{
"id" : "13",
"name" : "24 hours power back-up"
},
{
"id" : "14",
"name" : "A/C Power Backup Available"
},
{
"id" : "15",
"name" : "swimming pool"
},
{
"id" : "35",
"name" : "shoe cleaning service"
},
{
"id" : "36",
"name" : "Smoke detectors"
},
{
"id" : "37",
"name" : "Fire Extinguishers in each room"
},
{
"id" : "38",
"name" : "Pest Control"
},
{
"id" : "39",
"name" : "Conference / Banquet Hall"
},
{
"id" : "45",
"name" : "Restaurant"
},
{
"id" : "53",
"name" : "Anti-slip ramps"
},
{
"id" : "56",
"name" : "Tea/ Coffee Maker in the Rooms"
},
{
"id" : "59",
"name" : "Wi Fi Internet"
}
]
}
答案 0 :(得分:3)
find命令找到了包含设施对象的文档,其名称与您的搜索匹配。它不知道您只想查看负责该文档的单个子文档与您的搜索条件匹配。
您可以告诉mongo您希望使用位置$运算符来查看该元素。
db.mgh_facilities.find({"facilities.name": "Foreign exchange assistance"}, {"facilities.$": true})
答案 1 :(得分:0)
你可以试试这个
db.mgh_facilities.aggregate([
{
$unwind:"$facilities"
},
{
$match:{"facilities.name": "Foreign exchange assistance"}
},{
$project:{
_id:0,
facilities:1
}
}
])
结果:
{
"result" : [
{
"facilities" : {
"id" : "11",
"name" : "Foreign exchange assistance"
}
}
],
"ok" : 1
}