You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB聚合分组使用$function时报FieldPath不能以$开头错误

错误原因

你在$group阶段的_id分组字段定义中,直接将$function运算符作为了对象的键名。MongoDB不允许字段名以$开头,因此触发16410错误。

修复方案

你需要给$function的计算结果指定自定义的字段名作为键,$function本身作为值即可。以下是修复后的代码:

Attendance.aggregate([
  { $match: { cohort_id: cohort_id} },
  { $unwind: "$absences" },
  {
    $group: {
      _id: {
        term: "$absences.term",
        // 新增自定义字段名weekday作为键,$function作为值
        weekday: {
          $function: {
            body: function (day) {
              return day.getDay();
            },
            args: ["$absences.formatted_date.day"],
            lang: "js",
          }
        }
      },
      count: { $sum: 1 },
    },
  },
  { $sort: { count: 1 } },
])

优化方案(推荐)

自定义JS函数执行性能较低,你可以直接使用MongoDB原生的$dayOfWeek日期运算符实现相同逻辑,无需调用JS runtime:

Attendance.aggregate([
  { $match: { cohort_id: cohort_id} },
  { $unwind: "$absences" },
  {
    $group: {
      _id: {
        term: "$absences.term",
        // $dayOfWeek返回1(周日)-7(周六),减1后和getDay()返回的0(周日)-6(周六)完全一致
        weekday: { $subtract: [ { $dayOfWeek: "$absences.formatted_date.day" }, 1 ] }
      },
      count: { $sum: 1 },
    },
  },
  { $sort: { count: 1 } },
])

内容的提问来源于stack exchange,提问作者leila-m

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 06:15:02