gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:58:53 25 4
gpt4 key购买 nike

如果我有以下集合:

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

如果我只想通过 POST 返回带有餐厅 _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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com