【问题标题】:MongoDB: Querying multiple collections with two queries?MongoDB:用两个查询查询多个集合?
【发布时间】:2012-05-11 23:10:58
【问题描述】:

我有两个集合postsauthors。除了帖子数据之外,帖子文档还包含作者 _idDBref 链接 ID。我的收藏是这样的:

帖子

  "_id" : ObjectId("4fa12443d3269e98070013b4"),
  "author" : {
    "$ref" : "authors",
    "$id" : ObjectId("4fa1242bd3269e9807000023")
  },
  "post" : " mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem.",
  "post_title" : "Volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer",
  "date" : 1293803276,
  "rating" : 8,
  "comments" : [{
      "name" : "Doris Turner",
      "email" : "Hedda_Herman@.com",
      "upVotes" : 81,
      "downVotes" : 93,
      "comment_date" : 1111395830,
      "comment" : "consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at"
    }, {
      "name" : "Brenda Tyler",
      "upVotes" : 1,
      "downVotes" : 73,
      "comment_date" : 940325674,
      "comment" : "cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa."}],
  "tags" : ["tag1", "tag3"]
}  

我的作者收藏是这样的:

作者

{
  "_id" : ObjectId("4fa1242bd3269e9807000016"),
  "name" : "Kristina Chung ",
  "email" : "curran_ramos@google.co.id\r\n.dk",
  "age" : 60,
  "city" : "Copenhagen"
}

我正在尝试创建一个“关系”查询来查找: 评分大于 6 且小于 9 且作者年龄大于 19 且小于 25 的帖子。

我正在尝试汇总此数据,但似乎无法获得正确的数据。

第一个查询在我的帖子集合中,如下所示:

$query = array('rating' => array('$gte' => 6, '$lt' => 9), 'comments.upVotes' => array('$gt' => 2, '$lt' => 20));

我选择 author.$id 字段,它是对作者集合的引用。

然后我把所有的 $id 放在一个数组中:

while ($cursor->hasNext()): $document = $cursor->getNext();
    $authorID[] = $document['_id'];
endwhile;

然后我尝试在作者合集中使用此查询找到正确的数字

$query2 = array('age' => array('$gte' => 19, '$lt' =>100), '_id' => array('$in' => $authorID));
$cursor = q('author')->find($query2);

我尝试使用以下代码获取总数: $count = $cursor->count();但无论我尝试运行什么查询,我总是得到结果 0

我做错了什么,是否有可能创建这种查询,还是我必须在应用程序级别而不是数据库级别进行?

而且我非常了解嵌入式文档,但我希望将这两个集合分开而不是嵌入它。

希望任何人都可以帮助我。

真诚
- 梅斯蒂卡

【问题讨论】:

    标签: php json mongodb collections mongodb-query


    【解决方案1】:

    我不知道,但有时,游标方法似乎会丢失一些元素,所以我更喜欢使用 toArray():

    u = db.authors.find({"isActive":false}).toArray()
    idlist = []
    u.forEach(function(myDoc) { idlist.push(myDoc.ID ); } )
    db.posts.find({"AuthorID": {$in : idlist} } )
    
    
    u = db.authors.find({"isActive":false})
    idlist2 = []
    while (u.hasNext()) {idlist2.push(u.next()["ID"])};
    idlist.forEach(function(myDoc) { 
       if ( idlist2.indexOf(myDoc) == -1 ) 
           {print (myDoc)} 
    })
    

    打印 20 个元素!

    【讨论】:

      【解决方案2】:

      尝试在 MongoDB 中“创建一个“关系”查询”将是一个令人沮丧的练习。您的架构将一些信息(帖子的评分)存储在一个集合中,将其他信息(作者的年龄)存储在不同的集合中,但所有 MongoDB 查询都在单个集合上运行。除非您对数据进行非规范化(您说过不想这样做),否则您将需要一个两遍方法来完成这项工作。

      一种可行的方法是构建一个作者 ID 数组,并使用“$in”在帖子集合的查询中使用它。以下是使用 mongo shell 在 JavaScript 中的样子:

      > var authorList = [];
      > var authorCursor = db.authors.find({age:{$gt:19,$lt:25}},{"_id":1});
      > while(authorCursor.hasNext()){authorList.push(authorCursor.next()["_id"])};
      > db.posts.find({"author.$id":{$in:authorList},rating:{$gt:6,$lt:9}});
      

      第一行创建一个空数组。第二行创建一个光标,它将选择目标年龄范围内所有作者的_id 字段。第三行使用光标填充作者_ids 的数组。第四行显示所有符合您的目标条件的帖子:作者_id 在我们刚刚构建的列表中,并在您指定的范围内评分。

      【讨论】:

        猜你喜欢
        • 2016-09-27
        • 2019-05-09
        • 2020-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-24
        • 2020-07-17
        相关资源
        最近更新 更多