Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mongoose number of documents referenced in a collection

I have 2 collections

User:

email: { type: String, required: true, unique: true },
team: { type: ObjectId, ref: 'team', required: true},

And Team:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 name: { type: String, required: true },
 active: { type: Boolean, required: true, default: true},

I want to get all the teams and the number of users in that team, How would I approch this using Mongoose ?

>Solution :

Use the Teams model and perform an aggregate query.

First we join all users from the users collection. Then we create an extra field called user_amount in which we store the size of the users array. In the last step we remove the users property but if you need this array just remove the last step of this pipeline.

Playground

Teams.aggregate([
  {
    "$lookup": {
      "from": "users",
      "localField": "_id",
      "foreignField": "team",
      "as": "users"
    }
  },
  {
    "$addFields": {
      "user_amount": {
        "$size": "$users"
      }
    }
  },
  {
    "$unset": "users"
  }
])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading