繁体   English   中英

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

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

我有一个用户模式:

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

和课程模式:

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

如何获得拥有相同课程的用户总数? 就像如果一个课程名称“A”被 10 个不同的用户购买,如何获得这个总数?

使用$lookup ,您可以在users集合中查找courses集合的匹配记录。

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

工作示例

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

暂无
暂无

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

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