MongoDB:如何在JSON中返回特定字段和特定子文档

时间:2018-12-05 00:48:36

标签: javascript node.js mongodb mongodb-query

如果我有以下收藏:

{
    "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})
})

但不起作用。 任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

您的查询不正确。

匹配项应如下所示:

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。