MongoDB获得了我在项目管道中修改的字段总和
我想计算avgamount
作为sum 3字段= [balancelodeded + peripatorTueAmount -Walletusage]。 但是,这些字段可以为零,也可以根据条件为零(balancelodade,OperatoDueAmount,Walletusage)。我想总结应用条件后计算的最终值。是的,我需要从其他字段减去钱包。有人可以指导我如何在不更改项目管道中的字段名称的情况下执行此操作吗?
const result = await Bus.aggregate(
[
{
$match: { ...filter },
},
{
$project: {
_id: 1,
Amount1: '$Amount1',
Amount2: { $cond: [{ $in: ['example1', dueFieldsConfigs] }, '$Amount2', 0] },
Amount3: { $cond: [{ $in: ['example2', dueFieldsConfigs] }, '$Amount3', 0] },
Amount4: { $cond: [{ $in: ['example3', dueFieldsConfigs] }, '$Amount4', 0] },
avgAmount: { $sum: ['$Amount1', '$Amount2', '$Amount3'] },
},
},
{ $sort: sort },
{ $skip: skip },
{ $limit: limit },
],
);
I want to calculate avgAmount
as the sum 3 fields = [balanceLoaded + operatorDueAmount - walletUsage].
But these fields can either be zero or themselves (balanceLoaded, operatorDueAmount, walletUsage) depending on the condition. I want to sum up the final value which is calculated after applying the condition. And yes I need to subtract the walletUsage from other fields. Can someone guide me on how to do that without changing the names of fields in the project pipeline?
const result = await Bus.aggregate(
[
{
$match: { ...filter },
},
{
$project: {
_id: 1,
Amount1: '$Amount1',
Amount2: { $cond: [{ $in: ['example1', dueFieldsConfigs] }, '$Amount2', 0] },
Amount3: { $cond: [{ $in: ['example2', dueFieldsConfigs] }, '$Amount3', 0] },
Amount4: { $cond: [{ $in: ['example3', dueFieldsConfigs] }, '$Amount4', 0] },
avgAmount: { $sum: ['$Amount1', '$Amount2', '$Amount3'] },
},
},
{ $sort: sort },
{ $skip: skip },
{ $limit: limit },
],
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只是无法引用与创建它们相同的字段名称,最简单的方法就是在初始
$ project
阶段之后添加另一个阶段:如果您出于任何原因要放置它在同一阶段,您必须使用相同的条件来“计算”它们:
You just can't reference the same field names as you're creating them, the easiest way would be to just add another stage after the initial
$project
stage:If for whatever reason you want to put it in the same stage you'll have to use the same condition to "calculate" them: