Counting the number of instances where one array object proceeds another

I’ve been struggling on finding a clean way to map an array to a new array that illustrates the number of times any element within that array immediately precedes another.

For instance, say this is the original array:

{
   _id: objectId
   "myArray": Array
      0: Object
         name: "A"
      1: Object
         name: "B"
      2: Object
         name: "A"
      3: Object
         name: "B"
}

The desired outcome would be something like:

{
   _id: objectId
   "precedeCount": Array
      0: Object
         first: "A"
         second: "B"
         count: 2
      1: Object
         first: "B"
         second: "A"
         count: 1
}

I’m wondering if this is possible with the MongoDB aggregation pipelines, or if I should just go back to MapReduce.

Thanks in advance.

Pretty sure I wrote up something like this years ago… Check out this article

oh and the answer to this is always “never”! :slight_smile:

1 Like

I went ahead and wrote a three stage agg solution based on that old blog post:

{$set:{ pairs: {$map:{
     input:{$range:[0,{$subtract:[{$size:"$myArray"},1]}]}, 
     in:{$slice:["$myArray.name","$$this",2]}
}}}},
{$unwind:"$pairs"},
{$group:{_id:"$pairs", count:{$sum:1}}}

With your input this gives:

 { "_id" : [ "A", "B" ], "count" : 2 }
 { "_id" : [ "B", "A" ], "count" : 1 }

Thanks so much Asya this worked like a charm!

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.