2017-10-07 57 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

謝謝你的作品 –