简体   繁体   English

使用单个MONGODB组查询进行多个计数

[英]Multiple Counts using single MONGODB group query

I have a collection of Twitter data that I am grouping by day using MongoDB and the MongoDB PHP driver. 我收集了Twitter数据的集合,这些数据每天都使用MongoDB和MongoDB PHP驱动程序进行分组。 For each grouping, I'd like to calculate two counts based on subfield data. 对于每个分组,我想根据子字段数据计算两个计数。 One of the counts will be based on simply matching a string (I've figured that out). 计数之一将基于简单匹配一个字符串(我已经弄清楚了)。 The other will be need to check if an array contains a particular string. 另一个将需要检查数组是否包含特定字符串。 Is there code to do the second test? 是否有代码可以进行第二次测试?

Here's what I've got for the group() parameters: 这是我对group()参数的要求:

$initial = array(
  "count" => 0,
  "mentions" => 0
);

$reduce = new MongoCode(
  "
  function (doc, prev) { 
    if (doc.interaction.interaction.author.id == $twitter_id) {
      prev.count++; 
    }

    //Note, only returns true if first value in array is matched. How to return true if array contains value?
    if (doc.interaction.twitter.mention_ids == $twitter_id) {
       prev.mentions++;
    }
  }

");
if (doc.interaction.twitter.mention_ids == $twitter_id) {
   prev.mentions++;
}

Assuming mention_ids is an array in this example, I can't imagine how this condition returns true if "the first value in array is matched". 假设在这个例子中mention_ids的数组是一个数组,我无法想象如果“数组中的第一个值匹配”,这个条件如何返回true You're comparing an array to a string value (I assume that's what $twitter_id is). 您正在将数组与字符串值进行比较(我假设这就是$twitter_id的含义)。

To search the mention_ids array in JavaScript, you could either iterate through it and compare values (ideally break -ing out of the iteration after the first match), or utilize the Array.indexOf() method. 要在JavaScript中搜索mention_ids数组,您可以遍历它并比较值(最好是在第一个匹配项后break迭代),也可以使用Array.indexOf()方法。 As a rule of thumb, MDN's JavaScript portal is an excellent reference. 根据经验, MDN的JavaScript门户是一个很好的参考。

In addition to the core JavaScript API, you can find a list of other JavaScript functions at your disposal in map/reduce functions in the mapReduce command docs . 除了核心JavaScript API外,您还可以在mapReduce命令docs的 map / reduce函数中找到其他JavaScript函数的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM