2012-07-13 65 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}});