Glenn Flanagan
Glenn Flanagan

Reputation: 115

How do I aggregate the number of occurrences of an ObjectID in array?

I have two collections; users and communities. My users can be linked to many communities so I have linkedCommunities as an array in the User schema as such:

const userSchema = new Schema({
  linkedCommunities: [
    {
      type: mongoose.Schema.ObjectId,
      ref: 'Community'
    }
  ]
});

On my communities view I want to display the number of users linked to each community, so it would read something like:

| Community   | Number of users |
| ---------   | --------------- |
| Community 1 | 45              | 
| Community 2 | 78              |
| Community 4 | 107             | 

Ideally when I do a find on the Community model I want a field called something like linkedUserCount.

I'm sure I can achieve this using aggregate somehow but I'm struggling to find the right pipeline operators and order.

Upvotes: 1

Views: 80

Answers (2)

Galang ArbiS
Galang ArbiS

Reputation: 83

Here Maybe Can Help u,

users.aggregate([
{
    $lookup:
        {
            from: "Community",
            localField: "linkedCommunities",
            foreignField: "_id",
            as: "linkedcommunities"
        }}
,{
    $unwind: "$linkedCommunities"
},
{
    $group : {
        _id : "$linkedCommunities",
        count: { $sum: 1 }
    }
},
{
    $project: {
        _id: 0,
        community: "$_id",
        count: "$count"
    }
}]}

Upvotes: 2

mandar.gokhale
mandar.gokhale

Reputation: 1875

You can achieve required result by using following mongodb query:

db.users.aggregate( [ 
  { 
    $unwind : "$linkedCommunities" 
  },
  {
    $group : {
      _id : "$linkedCommunities",
      count: { $sum: 1 }
    }
  },
  {
    $project: {
      _id: 0,
      community: "$_id",
      count: "$count"
    }
  }
] )

Give it a try and let me know if you have any issues.

Upvotes: 1

Related Questions