如果我有以下收藏:
{
"restaurant": {
"_id": "5c0711f23533ef13a3e53d8b",
"name": "burger king",
"description": "american",
"reservations": [
{
"_id": "5c0712503533ef13a3e53d8c",
"time": "1:00 pm",
"people": 3
},
{
"_id": "5c0717129a8d7213e46d92da",
"time": "9:30 am",
"people": 10
},
{
"_id": "5c071960160f2a13f647e100",
"time": "12:30 am",
"people": 25
}
],
"__v": 0
}
}
如果我要发布,则仅返回带有餐厅的_id,名称,描述的特定预订,例如:
{
"restaurant": {
"_id": "5c0711f23533ef13a3e53d8b",
"name": "burger king",
"description": "american",
"reservations": [
{
"_id": "5c0717129a8d7213e46d92da",
"time": "9:30 am",
"people": 10
}
],
"__v": 0
}
}
最好的方法是什么?
我试过了:
Restaurant.find( {_id: ObjectID(id)}, {reservations : { $elemMatch: {time: time} }, {$elemMatch: {people: people}} } )
.then( (restaurant)=> {
res.send({restaurant})
})
但不起作用。
任何帮助,将不胜感激
最佳答案
您的查询不正确。
匹配应如下所示:
Restaurant.find( {_id: ObjectID(id)}, {
name: 1,
description: 1,
reservations : { $elemMatch: {time: time, people: people} } } )
.then( (restaurant)=> {
res.send({restaurant})
})
并确保_id实际上是ObjectID类型而不是String类型
以下查询工作正常(在本地测试):
db.getCollection('test').find({_id: '5c0711f23533ef13a3e53d8b'}, {name:1, description: 1, reservations: {$elemMatch: {people: 3, time: '1:00 pm'}}})
请注意,我使用的是字符串_id而不是对象ID。
关于javascript - MongoDB:如何在JSON中返回特定字段和特定子文档,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53623586/