2

I have a collection peopleColl containing records with people data. Each record is uniquely indexed by id and has a managers field of type array.

Example:

{
   id: 123,
   managers: [456, 789]
},
{
   id: 321,
   managers: [555, 789]
}

I want to write a single query to find all people with the same manager, for several ids (managers). So given [456, 555, 789] the desired output would be:

{
    456: 1,
    555: 1,
    789: 2
}

I can do it (slowly) in a for-loop in Python as follows:

idToCount = {id: peopleColl.count({"managers": id}) for id in ids}

Edit: I am primarily interested in solutions <= MongoDB 3.4

3 Answers 3

2

You can try below aggregation in mongodb 3.4.4 and above

db.collection.aggregate([
  { "$unwind": "$managers" },
  { "$group": { "_id": "$managers", "count": { "$sum": 1 }}},
  { "$group": {
    "_id": null,
    "data": {
      "$push": {
        "k": { "$toLower": "$_id" },
        "v": "$count"
      }
    }
  }},
  { "$replaceRoot": { "newRoot": { "$arrayToObject": "$data" }}}
])

Output

[
  {
    "456": 1,
    "555": 1,
    "789": 2
  }
]
Sign up to request clarification or add additional context in comments.

1 Comment

NB. ids are changed from int to string, however, this is a fast workable soln. ty
1

You can try below pipeline.

db.collection.aggregate([
  { "$unwind": "$managers" },
  { "$group": { "_id": "$managers", "count": { "$sum": 1 }}}
])

Output:

{'_id': 456, 'count': 1},
{'_id': 555, 'count': 1},
{'_id': 789, 'count': 2}

So you can loop through and create the Id-Count mapping

result = db.collection.aggregate([
      { "$unwind": "$managers" },
      { "$group": { "_id": "$managers", "count": { "$sum": 1 }}}
    ])

iD_Count = {}
result.forEach(function(d, i) {
iD_Count[d._id] = d.count;
})

iD_Count:

{
    456: 1,
    555: 1,
    789: 2
}

Comments

1

You can try below aggregation in 3.6.

db.colname.aggregate([
  {"$unwind":"$managers"},
  {"$group":{"_id":"$managers","count":{"$sum":1}}},
  {"$group":{
    "_id":null,
    "managerandcount":{"$mergeObjects":{"$arrayToObject":[[["$_id","$count"]]]}}
  }},
  {"$replaceRoot":{"newRoot":"$managerandcount"}}
])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.