2012-07-13 60 views
0

我有以下模式,博客收集& friendscoll如下的MongoDB:利用嵌套數組值查詢

blogpostcollection 
    { 
     "_id" : ObjectId("4fff0bf18bf0d19c4f1a5826"), 
     "author" : "joe", 
     "text" : "Here is the text...", 
     "userid" : 0 
    } 
    { 
     "_id" : ObjectId("4fff0bf18bf0d19c4f1a5827"), 
     "author" : "blake", 
     "text" : "Here is the text...", 
     "userid" : 1 
    } 
    { 
     "_id" : ObjectId("4fff0bf18bf0d19c4f1a5828"), 
     "author" : "joe", 
     "text" : "Here is the text...", 
     "userid" : 2 
    } 

myfriendscoll 
    { 
     "myid": 999, 
     "data": [ 
     { 
      "uid": 1, 
      "name": "Raul" 
     }, 
     { 
      "uid": 3, 
      "name": "John K" 
     } ] 
    } 

我想找到blogpostcollection,其中用戶ID存在的UID的所有文件,在myfriendscoll採集。 因此,實際上,像..

var user = db.myfriendscoll.findOne({"myid" : 999}, {"data.uid": 1}); 
db.blogpostcollection.find({"userid" : {$in : user.data.uid}}); 

這是不行的,但有一種方式來獲得它的工作?...謝謝!

回答

1

如果您使用的開發版本2.1或當您移動到2.2一旦它的發佈,你可以使用聚合框架來得到你想要從第一個查詢後面的格式:

var ret=db.myfriendscoll.aggregate([ 
      {$match:{"myid" : 999}}, 
      {$project:{_id:0,uid:"$data.uid"}} 
]); 
var uids=ret.result[0].uid; 
db.blogpostcollection.find({userid:{$in:uids}}) 
0

您需要將實際的uid值提取到數組中才能與$ in一起使用。試試這個:

var user = db.myfriendscoll.findOne({"myid" : 999}, {"data.uid": 1}); 
var uids = user.data.map(function(v){ return v.uid }); 
db.blogpostcollection.find({"userid" : {$in : uids}});