本文介绍了MongoDB:如何将仅出现在$ project中的字段相乘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我通过以下方式加入($ lookup)两个集合:
I'm joining ($lookup) two collection the following way :
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:
I want to calculate IncomeFromClient
by the mul of a const and a field that is been also calculated - TotalPurchasedLeads
, however it returns 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集合的大小?
How can I get the size of the $lookup collection when calculating a field that is being $projected ?
推荐答案
在我们可以在项目中使用键之后,请使用addFields关键字.
Please use addFields keyword after we can use key in project .
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"]
}
}
}
]
这篇关于MongoDB:如何将仅出现在$ project中的字段相乘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!