Mongodb位置操作员" $ "$sum操作不起作用



我正在开发一个电子商务web应用程序,我使用MEAN堆栈。我有一个订单集合,每个订单都有一个payment字段,该字段包含(affiliate marketersellersPaymentwebsitereferral(付款数据的子文档我的问题是关于sellersPayment字段,我有一个类似的数组

sellersPayment: [
{
amount: 50,
isPaid: false,
seller: ObjectId('seller 1 id'),
},
{
amount: 80,
isPaid: true,
seller: ObjectId('seller 2 id'),
},
]

问题是,我想查询在该数组内的字段seller上有特定卖家的订单,然后对amount字段求和这是我的方法:

await Order.aggregate([
{
$match: {
"payment.sellersPayment": {
$elemMatch: {
seller: ObjectId(user._id),
isPaid: false,
},
},
}      },
{
$group: {
_id: null,
confirmedBalance: { $sum: "$payment.sellersPayment.$.amount" },
},
},
{
$project: {
confirmedBalance: 1,
},
},
]);

我收到这个错误

"FieldPath字段名不能以"$"开头;有什么解决方案吗?

我得到这个错误"FieldPath字段名不能以"$"开头;有什么解决方案吗

confirmedBalance: { $sum: "$payment.sellersPayment.$.amount" },

这是无效语法,不能使用$sign访问数组元素,

很少有修复,

  • $match您的条件是正确的
  • $unwind解构sellersPayment阵列
  • $match再次匹配您的第一阶段条件以筛选sellersPayment的子文档
  • $group通过字段payment.sellersPayment.amount的零和量
  • $project显示必填字段
await Order.aggregate([
{
$match: {
"payment.sellersPayment": {
$elemMatch: {
seller: ObjectId(user._id),
isPaid: false
}
}
}
},
{ $unwind: "$payment.sellersPayment" },
{
$match: {
"payment.sellersPayment.seller": ObjectId(user._id),
"payment.sellersPayment.isPaid": false
}
},
{
$group: {
_id: null,
confirmedBalance: { $sum: "$payment.sellersPayment.amount" }
}
},
{
$project: {
_id: 0,
confirmedBalance: 1
}
}
])

游乐场

最新更新