简体   繁体   English

MongoDB:如何获取特定文档的计数?

[英]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?就像如果一个课程名称“A”被 10 个不同的用户购买,如何获得这个总数?

Using $lookup , you can look for the matching records of courses collection into the users collection.使用$lookup ,您可以在users集合中查找courses集合的匹配记录。

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

Working example工作示例

Read More on $lookup ; 阅读更多关于$lookup的信息;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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