gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:35:14 26 4
gpt4 key购买 nike

我有一个用户模式:

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

以及类(class)架构:

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

我怎样才能得到拥有相同类(class)的用户总数?例如,如果 10 个不同的用户购买了类(class)名称“A”,如何获得这个总数?

最佳答案

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

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

Working example

Read More$lookup;

关于javascript - MongoDB:如何获取特定文档的计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73542702/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com