2017-10-07 33 views
1

我有一个JSON对象在我的MongoDB如何只得到嵌套的JSON对象的MongoDB与node.js的

{ 
"_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然后检查的moduleId的数据,在包含JSON对象嵌套阵列模块,其是1111,1112,1121 ..等等 我怎么只能得到ModuleID:1111Bot_name:Scheduling bot

JSON对象到目前为止,我的查询是

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

这里的查询返回所有json里面的Modules

如何获得一个想要的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" 
     } 
    ] 
} 
+0

你的查询(''Modules.ModuleID:req.body.MID')应该是工作并过滤'Modules'阵列。所以技术上'data.Modules [0]'应该是你想要的。 –

+0

不起作用。它返回所有的模块json对象 –

+0

它的工作原理,如果我使用循环,但它会更容易查询,并得到我想要的确切JSON。这是可能的,或者我们只能将所有的对象作为我的模式? –

回答

2

您需要使用$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" 
       } 
      ] 
     } 
    ] 
} 
+0

谢谢你的作品 –