我有一个查询,当我使用$group时,一个错误显示"字段"$name必须是累加器对象",如果删除字段"$name",所有操作都很好,我try 只使用"name"而不是"$name",错误仍然存在.

   User.aggregate([
    {
      $match: {
        "storeKey": req.body.store        
      }
  },
  {
      $group: {
          "_id": "$_id",          
          "name": "$name",              
          "count": {
              "$sum": 1
          },
          "totalValue": {
              "$sum": "$value"
          }      
      }
  },
  {
    $sort: sort
  },
  {
     $skip: req.body.limit * req.body.page
  },
  {
     $limit: req.body.limit
  }
])...

推荐答案

有些聚合运算符只能在$group聚合中使用,命名为$group accumulators

正如你在这里使用$sum一样,你也必须使用name

{ "$group": {
  "_id": "$_id",
  "name": { "$first": "$name" },  //$first accumulator
  "count": { "$sum": 1 },  //$sum accumulator
  "totalValue": { "$sum": "$value" }  //$sum accumulator
}}

Accumulator is like array of Elements its Accumulates as Array. $first -> gives 1st name that goes in the group of names

例子:

Mongodb相关问答推荐

Mongo如何找到字段排除特殊字符

Mongo聚合项目数组交集

从MongoDB中的嵌套数组中提取找到的值及其索引

MongoDB即使在使用索引时也很慢

如何在 MongoDB 中的集合下查找同一文档

Mongo,通过 Lookup 计算多个文档中数组中的项目

如何在 kubernetes 中获取分片 mongodb 的备份

更新 Mongodb 中的多嵌套数组

使用 Node.js 通过 SSL 连接到 MongoDB

Mongoexport 在日期范围内使用 $gt 和 $lt 约束

更新 mongoengine 中的嵌入文档列表

MongoDB - 清除嵌套数组中的元素

将数据插入 MongoDB - 没有错误,没有插入

Spring Mongodb @DBREF

从性能Angular 来看 MongoDB 嵌入式与参考

Mongoose 中不同集合的相同模式

如何在第一个文档中恢复 MongoDB ChangeStream 而不仅仅是在我开始收听后更改

MongoDB:删除唯一约束

带有条件的MongoDB聚合查找

创建模型时出现mongoose错误