该字段必须是mongo中的累加器对象 [英] The field must be an accumulator object in mongo

查看:760
本文介绍了该字段必须是mongo中的累加器对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行聚合查询.我的要求是我要使用以下格式的文档:

I am performing an aggregation query.My requirement is that I have docs in following format:

{
"name":"a","age":20},
{
"name":"b","age":23},
{
"name":"a","age":26}

我需要对在名称字段中带有"a"的所有名称的年龄进行求和. 我正在执行以下操作,但它给我一个错误:字段'名称'必须是累加器对象":

I need to sum the ages of all names who have "a" in their name field. I am doing the following but it gives me an error that "The field 'name' must be an accumulator object":

db.collection('students').aggregate({
        $group: {"name": "a", "sum": {$sum: '$age'}}
    }, {
        $project: {sum: '$sum'}
    }, (e, d) => {
        if (!e) {
            var e = d.stream({transform: JSON.stringify});
            console.log("answer")
            console.log(e);
            deferred.resolve(e);
        } else {
            console.log(e)
        }
    })

推荐答案

我更改了您的聚合查询.请尝试以下操作:

I altered your aggregation query.Try as below:

db.collection('students').aggregate(
     [
       {
          $match: {
                 name: "a"
          }
       },
       {
         $group: {_id: "$name",
                  "sum": {
                     $sum: '$age'
                   }
                 }
        },
        {
          $project: {
                 sum: 1
        }
     ], (e, d) => {
        if (!e) {
            var e = d.stream({transform: JSON.stringify});
            console.log("answer")
            console.log(e);
            deferred.resolve(e);
        } else {
            console.log(e)
        }
    })

这篇关于该字段必须是mongo中的累加器对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆