Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays Mongodb:使用嵌套数组中的值进行查询_Arrays_Mongodb - Fatal编程技术网

Arrays Mongodb:使用嵌套数组中的值进行查询

Arrays Mongodb:使用嵌套数组中的值进行查询,arrays,mongodb,Arrays,Mongodb,我有以下模式、博客集和friendscoll,如下所示 blogpostcollection { "_id" : ObjectId("4fff0bf18bf0d19c4f1a5826"), "author" : "joe", "text" : "Here is the text...", "userid" : 0 } { "_id" : ObjectId("4fff0bf18bf0d19c4f1a5827"),

我有以下模式、博客集和friendscoll,如下所示

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"
        } ]
    }
我想在myfriendscoll集合中查找blogpostcollection中的所有文档,其中用户ID作为uid存在。 实际上,类似于

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

这不管用,但有办法让它发挥作用吗?…谢谢

您需要将实际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}});

如果您使用的是开发版本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}})