我正在使用Mongoose和Express创建API,并且需要您的帮助才能在hotels
数组中查找特定文档。我需要找到与id
特定值匹配的文档。
这是模式:
{
"_id": "5e181fed9fc1883a69797e3a",
"hotels": [
{
"name": "Hotel Emperador",
"stars": 4,
"price": 1596,
"imagen": "https://i.ibb.co/RHYqxjL/hotel1.jpg",
"id": 1
},
{
"name": "Hotel Sonesta",
"starts": 4,
"price": 2400,
"imagen": "https://i.ibb.co/kx06vbZ/hotel2.jpg",
"id": "sonesta"
},
{
"name": "Hotel Soratama",
"stars": 3,
"price": 1000,
"imagen": "https://i.ibb.co/hx0Txk6/hotel3.jpg",
"id": "3"
}
]
}
我的get_id
api中需要类似此响应的内容,但是我做不到,您能帮我吗?
{
"name" : "Hotel Emperador",
"stars" : 4,
"price" : 1596,
"imagen" : "https://i.ibb.co/RHYqxjL/hotel1.jpg",
"id": 1
}
您可以使用聚合框架来检索文档
hotelModel.aggregate([{
$match:{
_id: "5e181fed9fc1883a69797e3a"
}
},{ $project: {
hotels: { $filter: {
input: '$hotels',
as: 'hotel',
cond: { $eq: ['$$hotel.id', 1]}
}},
_id: 0
}
},{
$unwind:"$hotels"
}])
https://mongoplayground.net/p/ka5WAdCvuZG
参考资料:
https://docs.mongodb.com/manual/reference/operator/aggregation/filter/ https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句