我通过以下方式加入($lookup)两个集合:
const LEAD_PRICE = ....; // doesn't matter
Client.aggregate(
[
{
$lookup: {
from: "clientboughtleads",
localField: "_id",
foreignField: "Client",
as: "ClientLeads"
}
},
{
$project: {
ClientId: "$_id",
RegistrationDate: "$date",
TotalPurchasedLeads: {
$size: "$ClientLeads"
},
IncomeFromClient: { // This one is always undefined
$multiply: [LEAD_PRICE / 2, "$TotalPurchasedLeads"]
}
}
}
]
我想通过 const 和已计算的字段 - TotalPurchasedLeads
的乘数来计算 IncomeFromClient
,但它返回 NULL :
[
[0] {
[0] _id: 5e0e43ae82a71e0017dccb20,
[0] ClientId: 5e0e43ae82a71e0017dccb20,
[0] RegistrationDate: 2020-01-02T21:25:34.000Z,
[0] TotalPurchasedLeads: 4,
[0] IncomeFromClient: null // This one is not calculated
[0] }
[0] ]
在计算 $projected 字段时如何获取 $lookup 集合的大小?
我们可以在项目中使用 key 后,请使用 addFields 关键字。
const LEAD_PRICE = ....; // doesn't matter
Client.aggregate(
[
{
$lookup: {
from: "clientboughtleads",
localField: "_id",
foreignField: "Client",
as: "ClientLeads"
}
},
{
$addFields: {
TotalPurchasedLeads: {
$size: "$ClientLeads"
}
}
},
{
$project: {
ClientId: "$_id",
RegistrationDate: "$date",
TotalPurchasedLeads:1,
IncomeFromClient: { // This one is always undefined
$multiply: [LEAD_PRICE / 2, "$TotalPurchasedLeads"]
}
}
}
]
我是一名优秀的程序员,十分优秀!