gpt4 book ai didi

json - node.js如何只获取MongoDB嵌套JSON对象的数据

转载 作者:可可西里 更新时间:2023-11-01 10:14:16 26 4
gpt4 key购买 nike

我的 MONGODB 中有一个 JSON 对象

{
"_id" : ObjectId("59d4b9848621854d8fb2b1e1"),
"Bot_name" : "Scheduling bot",
"Modules" : [
{
"ModuleID" : "1111",
"ModuleStatement" : "This is a Sceduling bot, Would you like to book a flight?",
"_id" : ObjectId("59d4b9968621854d8fb2b1e3"),
"ModuleResponse" : [
{
"Response" : "yes",
"TransBotID" : "1112"
},
{
"Response" : "no",
"TransBotID" : "1113"
}
]
},
{
"ModuleID" : "1112",
"ModuleStatement" : "Where would you like to go? New York ? LA?",
"_id" : ObjectId("59d4b9968621854d8fb2b1e3"),
"ModuleResponse" : [
{
"Response" : "New York",
"TransBotID" : "1121"
},
{
"Response" : "LA",
"TransBotID" : "1122"
}
]
},
{
"ModuleID" : "1121",
"ModuleStatement" : " New York..",
"_id" : ObjectId("59d4b9968621854d8fb2b1e3"),
"ModuleResponse" : []
},
{
"ModuleID" : "1121",
"ModuleStatement" : " New York..",
"_id" : ObjectId("59d4b9968621854d8fb2b1e3"),
"ModuleResponse" : []
}
}

我进行的查询将首先检查 Bot_name,然后检查包含 1111、1112、1121 等 JSON 对象的嵌套数组模块中的 ModuleID我如何只获取 Bot_name:Scheduling botModuleID:1111 的 json 对象

到目前为止我的查询是

botSchema.findOne({ Bot_name: req.body.Name ,'Modules.ModuleID':req.body.MID}, function (err, data) {
console.log(data)
}

此处查询返回模块中的所有json

如何只得到一个想要的json对象?像这样

{
"ModuleID" : "1111",
"ModuleStatement" : "This is a Sceduling bot, Would you like to book a flight?",
"_id" : ObjectId("59d4b9968621854d8fb2b1e3"),
"ModuleResponse" : [
{
"Response" : "yes",
"TransBotID" : "1112"
},
{
"Response" : "no",
"TransBotID" : "1113"
}
]
}

最佳答案

您需要使用 $elemMatch 来过滤子数组。

db.botSchema.findOne( 
{ Bot_name: "Scheduling bot"}
, { 'Modules': { $elemMatch:{'ModuleID':"1111"} } }
, function (err, data) { console.log(data) })

结果:

{
"_id" : ObjectId("59d4b9848621854d8fb2b1e1"),
"Modules" : [
{
"ModuleID" : "1111",
"ModuleStatement" : "This is a Sceduling bot, Would you like to book a flight?",
"_id" : ObjectId("59d4b9968621854d8fb2b1e3"),
"ModuleResponse" : [
{
"Response" : "yes",
"TransBotID" : "1112"
},
{
"Response" : "no",
"TransBotID" : "1113"
}
]
}
]
}

关于json - node.js如何只获取MongoDB嵌套JSON对象的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46619514/

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