如何使用node.js仅获取嵌套JSON对象MongoDB的数据
我的MONGODB中有一个JSON对象如何使用node.js仅获取嵌套JSON对象MongoDB的数据,json,node.js,mongodb,Json,Node.js,Mongodb,我的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
{
"_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_名称,然后检查包含JSON对象的嵌套数组模块中的ModuleID,这些模块是11111121121。。等等
如何仅获取Bot的ModuleID:1111
的json对象(名称:Scheduling Bot
到目前为止,我的问题是
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"
}
]
}
]
}
您的查询('Modules.ModuleID:req.body.MID
)应该可以工作并过滤模块
数组。所以从技术上讲,data.Modules[0]
应该是您想要的。不起作用。如果我用于循环,它将返回json objectit可以工作的所有模块,但是查询和获取所需的确切json会更容易。这是可能的还是我们只能将所有对象作为我的模式?