gpt4 book ai didi

node.js - MongoDB : How to multiply a field that appears only in $project?

转载 作者:太空宇宙 更新时间:2023-11-03 23:12:40 25 4
gpt4 key购买 nike

我通过以下方式加入($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"]
}
}
}
]

关于node.js - MongoDB : How to multiply a field that appears only in $project?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59576585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com