简体   繁体   中英

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

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?

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 ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM