K. Barresi
K. Barresi

Reputation: 1315

Finding Mongo ObjectIds That Occur in an Array Together

I have a document with a schema containing the following:

{
    ...
    entities : [ ObjectId ]
}

My goal is to find which ObjectIds in the entities array appear most with a given ObjectId. For example, if I supply an ID of 12345 (or whatever), I would want to get back a list of ObjectIds that appear alongside 12345 in the entities across all documents with 12345 in the entities array, along with the combined number of times they appear together.

I think I have to use the aggregation framework, where my matcher would just select all documents where the ObjectId of 12345 appears in the entities array.

For the grouping operation, I think would need to go through each of the matched documents, and keep a global tally of of how many times each ObjectId appears in the entities array, so the output would be something like:

[
    { ObjectId(23456) : 53 },
    { ObjectId(34567) : 30 },
    { ObjectId(45678) : 16 }
]

I'm not quite sure how to do that grouping operation though. Any suggestions?

Upvotes: 0

Views: 34

Answers (1)

Poorna Subhash
Poorna Subhash

Reputation: 2128

try following.


var pipeline ;

pipeline = [
  {
    $match: {entities: '12345'}
  },
  {
    $unwind: '$entities'
  },
  {
    $group: {_id: '$entities', count: {$sum: 1}},
  },
  {
    $sort: {'count': -1}
  }

];
db.mycollection.aggregate(pipeline)
 

Upvotes: 1

Related Questions