簡體   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