我有两个系列
第1个用户和第2个班次
当我用查找和展开表达式编写如下查询时。
results.users = await model.aggregate([
{
$match: filter,
},
{
$lookup: {
from: "shifts",
localField: "_id",
foreignField: "employeeId",
as: "shifts",
},
},
{
$unwind: { path: "$shifts", preserveNullAndEmptyArrays: true },
},
]);
我得到的响应如下所示,我多次获取最后一个用户,因为它有多个日期的多个班次数据,而在前两个数据中,我没有获取任何班次数据,因为该用户的数据不存在,这是正确的。
[
{
_id: "60dd781c4524e6c116e2336d",
workerFirstName: "MADASWAMY",
workerSurname: "KARUPPASWAMY",
workerId: "1002",
},
{
_id: "60dd781d4524e6c116e234d4",
workerFirstName: "AMIT",
workerSurname: "SHAH",
workerId: "1001",
},
{
_id: "60dd781d4524e6c116e23642",
workerFirstName: "DEVELOPER",
workerSurname: "DEVELOPER",
workerId: "7738",
shifts: {
_id: "634d8d3ce596dd34c9532d7d",
month: "October",
workerId: "7738",
date: "2022-10-01T00:00:00.000Z",
},
},
{
_id: "60dd781d4524e6c116e23642",
workerFirstName: "DEVELOPER",
workerSurname: "DEVELOPER",
workerId: "7738",
shifts: {
_id: "634d8d3ce596dd34c9532d6d",
month: "October",
workerId: "7738",
date: "2022-10-02T00:00:00.000Z",
},
},
{
_id: "60dd781d4524e6c116e23642",
workerFirstName: "DEVELOPER",
workerSurname: "DEVELOPER",
workerId: "7738",
shifts: {
_id: "634d8d3ce596dd34c9532d5c",
month: "October",
workerId: "7738",
date: "2022-10-31T00:00:00.000Z",
},
},
]
我在写下面的查询时,用match表达式经过查找和展开。
results.users = await model.aggregate([
{
$match: filter,
},
{
$lookup: {
from: "shifts",
localField: "_id",
foreignField: "employeeId",
as: "shifts",
},
},
{
$unwind: { path: "$shifts", preserveNullAndEmptyArrays: true },
},
{
$match: {
"shifts.date": new Date(formatTimeToIso(new Date())),
},
},
]);
我得到的响应只有1个数据,这也是正确的,因为匹配表达式是这样工作的。
[
{
_id: "60dd781d4524e6c116e23642",
workerFirstName: "DEVELOPER",
workerSurname: "DEVELOPER",
workerId: "7738",
shifts: {
_id: "634d8d3ce596dd34c9532d5d",
month: "October",
workerId: "7738",
date: "2022-10-31T00:00:00.000Z",
},
},
]
但我想要的响应应该与下面的响应类似,因此,可以在表达式中添加或删除任何内容,以便以所需的格式获取数据
[
{
_id: "60dd781c4524e6c116e2336d",
workerFirstName: "MADASWAMY",
workerSurname: "KARUPPASWAMY",
workerId: "1002",
shifts:{}
},
{
_id: "60dd781d4524e6c116e234d4",
workerFirstName: "AMIT",
workerSurname: "SHAH",
workerId: "1001",
shifts:{}
},
{
_id: "60dd781d4524e6c116e23642",
workerFirstName: "DEVELOPER",
workerSurname: "DEVELOPER",
workerId: "7738",
shifts: {
_id: "634d8d3ce596dd34c9532d5d",
month: "October",
workerId: "7738",
date: "2022-10-31T00:00:00.000Z",
},
},
]
1条答案
按热度按时间jjhzyzn01#
假设在
$lookup
阶段之后,您将得到以下结果:在
$lookup
阶段之后:$set
-通过$filter
过滤文档来设置shifts
数组。$unwind
-解构shifts
数组。