我正在开发一个电子商务web应用程序,我使用MEAN堆栈。我有一个订单集合,每个订单都有一个payment
字段,该字段包含(affiliate marketer
、sellersPayment
、website
、referral
(付款数据的子文档我的问题是关于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
}
}
])
游乐场