我有两个集合作为用户和用户_课程.user_courses集合是一个多对多连接表.我需要通过注册的分页当然过滤用户.
用户集合如下所示:
[
{
"_id": ObjectId("123"),
"name": "Lorem Ipsum",
"email": "lorem@ipsum.com"
},
{
"_id": ObjectId("234"),
"name": "Lorem Ipsum",
"email": "lorem@ipsum.com"
},
{
"_id": ObjectId("345"),
"name": "Lorem Ipsum",
"email": "lorem@ipsum.com"
},
...
]
和User_Course集合类似于:
[
{
"_id": ObjectId("12345"),
"userId": ObjectId("123"),
"courseId": ObjectId("111"),
},
{
"_id": ObjectId("23456"),
"userId": ObjectId("123"),
"courseId": ObjectId("222"),
},
{
"_id": ObjectId("34567"),
"userId": ObjectId("123"),
"courseId": ObjectId("333"),
},
{
"_id": ObjectId("45678"),
"userId": ObjectId("234"),
"courseId": ObjectId("222"),
},
{
"_id": ObjectId("56789"),
"userId": ObjectId("345"),
"courseId": ObjectId("111"),
},
{
"_id": ObjectId("67890"),
"userId": ObjectId("345"),
"courseId": ObjectId("222"),
},
...
]
下面是我的代码:
const filterObj = {
"$or": [
{
"name": {
$regex: searchKey
}
},
{
"email": {
$regex: searchKey
}
}
]
}
Users.aggregate([
{ $match: filterObj },
{ $sort: { createdAt: -1 } },
{ $skip: skip },
{ $limit: limit },
{
$lookup: {
from: 'user_courses',
localField: '_id',
foreignField: 'userId',
as: 'userCourses',
pipeline: [
{
$match: {
$expr: {
$and: [
{
$eq: [
"$courseId",
new mongoose.Types.ObjectId(courseId)
]
}
]
}
}
}
]
}
},
{
$unwind: "$userCourses"
}
])
使用此代码,它将获取前10个项目(限制:10,跳过:0),然后使用管道中的匹配过滤结果.如果我删除展开选项,它只在查找值内应用过滤器,并返回所有用户,即使userCourse查找为空.
如何在排序、跳过和限制之前按已注册课程过滤用户?