简体   繁体   中英

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. 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:

$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". You're comparing an array to a string value (I assume that's what $twitter_id is).

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. As a rule of thumb, MDN's JavaScript portal is an excellent reference.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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