如何获取嵌套的JSON对象MongoDB的数据与node.js
我在我的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,然后检查包含JSON对象是1111,1112,1121的嵌套数组模块中的ModuleID。那么我如何只获取ModuleID:1111
的JSON对象ModuleID:1111
的Bot_name:Scheduling bot
到目前为止我的查询是
botSchema.findOne({ Bot_name: req.body.Name ,'Modules.ModuleID':req.body.MID}, function (err, data) { console.log(data) }
这里的查询返回Modules
内的所有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" } ] } ] }