我有两个集合,如下,
用户收藏
{
"_id" : ObjectId("5af2e946aa546125b5de85cc"),
"name" : "Sudhin",
"email" : "abc@abc.com",
"roles" : [
"Reader",
"Instructor"
],
"createdAt" : ISODate("2018-05-09T12:27:50.651Z"),
"updatedAt" : ISODate("2018-05-16T09:22:07.280Z")
},
{
"_id" : ObjectId("5af2f3a6efb83031faaa3d82"),
"name" : "Rahul",
"email" : "abcd@abc.com",
"roles" : [
"Reader",
"Instructor"
]
"createdAt" : ISODate("2018-05-09T13:12:06.518Z"),
"updatedAt" : ISODate("2018-05-16T09:22:07.281Z")
}
计划程序集合
{
"_id" : ObjectId("5afd763b8fad29597e1b85ed"),
"title" : "ILT Course",
"type" : "Course",
"ilt" : {
"instructorId" : ObjectId("5af2e946aa546125b5de85cc"),
"type" : "ILT-Offline",
"instructorName" : "Sudhin",
"place" : "*******",
"description" : "******"
},
"startDate" : ISODate("2018-05-10T11:00:00.000Z"),
"endDate" : ISODate("2018-05-15T12:00:00.000Z"),
"createdAt" : ISODate("2018-05-17T12:31:55.574Z"),
"updatedAt" : ISODate("2018-05-17T12:31:55.575Z")
}
在调度程序集合中,“ilt.instructorId”是用户的referenceId。
计划程序集合包含特定用户计划的所有详细信息。
startDate是特定计划的开始日期和时间。 endDate是特定时间表的结束日期和时间。
当我将startDate传递给endDate(2018-05-05 00:00 - 2018-05-10 00:00)时,我想要获取具有角色指导员的所有用户以及那些之间没有任何预定课程的用户日期。
例如:如果我通过2018-05-05 00:00 - 2018-05-10 00:00,它应该返回 以下文件
{
"_id" : ObjectId("5af2f3a6efb83031faaa3d82"),
"name" : "Rahul",
"email" : "abcd@abc.com",
"roles" : [
"Reader",
"Instructor"
]
"createdAt" : ISODate("2018-05-09T13:12:06.518Z"),
"updatedAt" : ISODate("2018-05-16T09:22:07.281Z")
}
我尝试了以下查询
UserModel.query().aggregate([
{ $match: { roles: { $in: ['Instructor'] } } },
{
$lookup: {
from: "schedulers",
localField: "_id",
foreignField: "ilt.instructorId",
as: "schedule"
}
},
{
$match: {
"schedule.type": "Course",
$and: [
{ 'schedule.endDate': { $not: { $lte: new Date("2018-05-12T12:00:00.000Z") } }},
{ 'schedule.startDate': { $not: { $gte: new Date("2018-05-06T11:00:00.000Z") } }},
]
}
},
{
$project: {
_id: 1,
name: 1,
empId: 1,
startDateTime: "$schedule.startDate",
endDateTime: "$schedule.endDate",
}
}])
答案 0 :(得分:0)
请查看以下查询帮助您:
db.getCollection('user').aggregate([
{ $match: { roles: { $in: ['Instructor'] } } },
{
$lookup: {
from: "schedulers",
localField: "_id",
foreignField: "ilt.instructorId",
as: "schedule"
}
},
{
$match: {
"schedule.type": "Course",
$or: [
{ 'schedule.startDate': { $lt: new Date("2018-05-08T11:00:00.000Z") }},
{ 'schedule.endDate': { $gt: new Date("2018-05-14T12:00:00.000Z") }},
]
}
},
{
$unwind: {
path: '$schedule',
preserveNullAndEmptyArrays: true,
},
},
{
$project: {
_id: 1,
name: 1,
empId: 1,
schedule:'$schedule',
startDateTime: "$schedule.startDate",
endDateTime: "$schedule.endDate",
}
}])