【问题标题】:Mongodb positional operator " $ " with $sum operation not working带有 $sum 操作的 Mongodb 位置运算符“$”不起作用
【发布时间】:2021-07-26 03:43:58
【问题描述】:

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

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

问题是我想查询在该数组 ant 内的 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 字段名称不能以 '$' 开头" 有什么解决办法吗?

【问题讨论】:

  • 你能提供一个输入和输出的例子吗?此外,您不能使用两个位置运算符$。尝试在"$payment.sellersPayment.$.amount"中删除其中一个@
  • 非常感谢,我将最后一条评论标记为已接受的答案。

标签: mongodb express mongoose aggregation-framework


【解决方案1】:

我收到此错误“FieldPath 字段名称可能不以'$'开头”任何解决方案?

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

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

修复很少,

  • $match你的条件是正确的
  • $unwind解构sellersPayment数组
  • $match 再次匹配您的第一阶段条件以过滤 sellersPayment 的子文档
  • $group 使用字段 payment.sellersPayment.amount 通过 null 和总和
  • $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
    }
  }
])

Playground

【讨论】:

    猜你喜欢
    • 2021-09-18
    • 2017-02-14
    • 2015-01-25
    • 2018-04-27
    • 2022-11-15
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    相关资源
    最近更新 更多