Ghasem Khalili
Ghasem Khalili

Reputation: 973

How can I get count of document in one to many relation with mongoose

I have two schemas.

// tutorial
export const TutorialSchema = new mongoose.Schema({
    title: String,
    author: String,
    tags: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Tag"
        }
    ]
})

// tag
export const TagSchema = new mongoose.Schema({
    name: String,
    companyId: Number
})


constructor(@InjectModel('Tutorial') private readonly _tutorialModel: Model<any>) { }

I want to get count of tags for each tutorial (in one query). How can I do that ? I know how to get list of tutorial.

const result = await _tutorialModel.find()

Upvotes: 0

Views: 426

Answers (1)

shubham
shubham

Reputation: 457

You can use group aggregation in the following way -


_tutorialModel.aggregate([
   {
      $project: {
         title: 1,
         _id:1,
         numberOfTags: { $cond: { if: { $isArray: "$tags" }, then: { $size: "$tags" 
       }, else: "NA"} }
      }
   }
] )

For Size operator you need to ensure first that tags is always an array! If for any reason tags is not present then error will be thrown.

If you make sure tags will be always present and is an array then you can simplify to following -


_tutorialModel.aggregate([
   {
      $project: {
         title: 1,
         _id:1,
         numberOfTags: {$size: "$tags"}
      }
   }
] )

Take a look at -

Size aggregation operator - https://www.mongodb.com/docs/manual/reference/operator/aggregation/size/

Upvotes: 1

Related Questions