node.js - MongoDB:如何将仅出现在 $project 中的字段相乘?
问题描述
我通过以下方式加入($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"]
}
}
}
]
我想IncomeFromClient
通过 mul 的 const 和一个也被计算的字段来计算 - 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"]
}
}
}
]
推荐阅读
- java - 检查是否有人在井字游戏中获胜的功能不起作用(JAVA)
- angular - 将引导程序添加到 Angular 12.1.4 - 无法解析依赖树
- c# - C# editorconfig - 如何根据继承指定规则
- azure-data-factory - 将嵌套数组映射到接收器列
- google-colaboratory - 如何更新 Google Colab 的 Python 版本?
- python - 为什么 ax2 在 matplotlib 子图中写在 ax1 的 y 轴上?
- html - 开始溢出时完全隐藏列
- google-sheets - 当数据在另一个工作表中时,如何从文本字符串中提取特定文本?
- python - 使用 XPath 进行网页抓取 - 复制文本 xpath 后找不到元素
- python - 如何将文件名更改为 Post Form 的标题?