我通过以下方式加入($ 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和也计算出的字段mul来计算
IncomeFromClient
-TotalPurchasedLeads
,但是它返回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集合的大小?
最佳答案
我们可以在project中使用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"]
}
}
}
]
关于node.js - MongoDB:如何乘以仅出现在$ project中的字段?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59576585/