The field "$name" must be an accumulator object
There are some aggregation operators that can only be used in $group
aggregation and named as $group accumulators
Just as you used $sum
here you have to use for the name
key as well
{ "$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
Example:so if you have $_id
same but different name ["Darik","John"]
specifying $first
will give Darik & similarly $last
will give John
db.faq_feedback.aggregate({ $lookup:{ "from":"faq", "localField":"question_id", "foreignField":"_id", "as":"faq" }},{ $unwind:"$faq"},{ $project:{ "question_id":1, "lang":"$faq.lang", "feedback":"$faq.feedback", "question":"$faq.question", "yes":{ "$cond":[ { "$eq":[ "$feedback", "yes" ] }, 1, 0 ] }, "no":{ "$cond":[ { "$eq":[ "$feedback", "no" ] }, 1, 0 ] } }},{ $group:{ "_id":"$question_id", "yes":{ "$sum":"$yes" }, "no":{ "$sum":"$no" }, "question":{"$first":"$question"}, "lang":{"$first":"$lang"} }},{ $limit:10000},{ $skip:0})
$group: { _id:"$_id", "name" :{ $last: '$name' }, "count" : { $sum: 1 }, "totalValue": { "$sum": "$value" }}