Home > OS >  MongoDB: how to get the count of a particular document?
MongoDB: how to get the count of a particular document?

Time:08-31

I have a schema of USERS:

const signUpTemplate = new mongoose.Schema({
  fullname: {
    type: String,
  },
  purchasedCourses: {
    type: Array,
    default: [] //Here courseIdList is pushed with unique ID and course name
  }
});

And a schema of courses:

const courseIdList = new mongoose.Schema({
  _id: { type: String },
  courseName: { type: String },
  purchaseDate: {
    type: Date,
    default: Date.now,
  },
});

How can I get the total count of users having a same course? Like if a course name 'A' is purchased by 10 different users how can get this total number?

CodePudding user response:

Using $lookup, you can look for the matching records of courses collection into the users collection.

db.courses.aggregate(
   [{ $lookup: { 
      from: "users", 
      localField: "_id", 
      foreignField: "purchasedCourses._id", 
      as: "coursesCount" 
   }}, 
   { $addFields: { "coursesCount": { $size: "$coursesCount" } } }]
)

Working example

Read More on $lookup;

  • Related