2012-11-26 50 views
1

我有我的架構設置是這樣的:MongoDB中找到子文檔IDS

{ 
_id:1234, 
friends: [ 
      { 
      "fid":1235 
      "is_user":true 
      }, 
      { 
      "fid":1236 
      "is_user":true 
      }, 
      { 
      "fid":1235 
      "is_user":false 
      } 
      ] 
} 

我的要求是,給定一個_id,我需要找到所有的朋友IDS (fid)誰擁有is_user設置爲true。

我試過如下:

db.users.find({ friends: { $elemMatch : { is_app_user: true}}}); 

似乎給我回了整個集合中的結果,但我想它的ID。所以我試過這個:

db.users.find({_id:1234},{friends: { $elemMatch : { is_app_user: true}}}); 

但這並沒有給我什麼。另外,我需要的只是fid。有人能幫我解決這個問題嗎?

回答

8

在這樣的地方,你想比從數組只是第一匹配元素的更多的情況下,你必須使用aggregation framework代替find

db.users.aggregate([ 
    // Find the matching document 
    { $match: { _id: 1234 }}, 
    // Duplicate the document for each element of friends 
    { $unwind: '$friends' }, 
    // Filter the documents to just those where friends.is_user = true 
    { $match: { 'friends.is_user': true }}, 
    // Only include fid in the results 
    { $project: { _id: 0, fid: '$friends.fid'}} 
]); 
+0

啊,打我吧! +1 –

+0

謝謝JohnnyHK ..(和Chris :)) – sharath