2016-02-26 110 views
0

我有以下格式的文件嵌套:嵌套文檔中的MongoDB陣列讀取節點

{ 
    _id: "1234567890", 
    course: {content: [{ id: 1, 
          children:[{ 
          id: 1111 
          }, 
          { 
          id: 2222 
          } 
           { 
          id: 3333 
          }] 
         }, 
         { id: 2, 
          children:[{ 
          id: 4444 
          }, 
          { 
          id: 5555 
          } 
           { 
          id: 6666 
          }] 
         } 

       ]} 

} 

我試圖查詢基於ID(course.content.children.id)兒童使用以下從Node.js的代碼:

var query = { 
      'course.content.children.id': quizId, 
}; 
var option = { 
     'course.content.children.$': 1, 
     }; 
db.getEntityWithOption(tablename,query,option,function(data,err){ 
    res.send(data.course.content[0].children); 
}); 

db.getEntityWithOption是db.find()方法的頂部包裝方法。當我打電話與測驗ID爲1的方法,上面的代碼返回我下面的完整陣列:`

      { id: 1, 
          children:[{ 
          id: 1111 
          }, 
          { 
          id: 2222 
          } 
           { 
          id: 3333 
          }] 
         } 

但我只需要ID爲1111而不是競爭數組的數組特定元素。任何救世主都可以告訴我我在這裏做錯了什麼。 TIA :)

+0

可能duplidate http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an -object-array-in-mongodb-collection – Ben

+0

@Ben我已經通過鏈接,它不適合我,它返回我完整的數組集,如上所述。 –

回答

0

那麼你可以找到你的ID從孩子想對象,然後將結果發送像什麼:

res.send(data.course.content[0].children[0]); 

或者,你可以,如果它不是在第一個數組元素與發現for循環然後發送結果。

或者你可以嘗試在你的查詢中使用$ elemMatch,但是你將不得不使用聚合。

順便說一句,在我看來,你不應該使用如此深的嵌套文件因爲它將很難運行復雜的查詢。

0

請嘗試通過aggregation,與$unwind$match

> db.course.aggregate([ 
         // unwind the `content` array 
         {$unwind: '$course.content'}, 
         // unwind the `children` array of `content` 
         {$unwind: '$course.content.children'}, 
         // match the id with `1111` 
         {$match: {'course.content.children.id': 1111}}]); 

結果:

{ "_id" : ObjectId("56d058d22750efa1f9dc3772"), "course" : { "content" : { "id" : 1, "children" : { "id" : 1111 } } } } 

爲了滿足你的要求,只返回了1111陣列,我們可以做到這一點通過$project

> db.course.aggregate([{$unwind: '$course.content'}, 
         {$unwind: '$course.content.children'}, 
         {$match: {'course.content.children.id': 111}}, 
         {$project: {_id: 0, arr: '$course.content.children'}}]); 

結果:

{ "arr" : { "id" : 111 } } 
-1

你想要的屬性查詢,但你不知道哪個contentchildren陣列的孩子具備所要求的ID。 MongoDB中提供positional operator

查詢應該這樣定義:的

var query = { 
    'course.content.$.children.$.id': quizId, 
};