mongodb - $sum using Mongo DB aggreagation -
i have document follows:
{_id:1,"$field1":10,"$field2":20}
through mongo db java driver, can update documents new field called $total sum of field1 , field2
the equivalent in relation database like
update table set total=field1+field2
is same possible using mongo db java driver without fetching records 1 one.
i have tried following link , doesnt give result specified in link
https://docs.mongodb.org/manual/reference/operator/aggregation/sum/
db.students.insert({ "_id": 1, "quizzes": [ 10, 6, 7 ], "labs": [ 5, 8 ], "final": 80, "midterm": 75 }); db.students.insert({ "_id": 2, "quizzes": [ 9, 10 ], "labs": [ 8, 8 ], "final": 95, "midterm": 80 }); db.students.insert({ "_id": 3, "quizzes": [ 4, 5, 5 ], "labs": [ 6, 5 ], "final": 78, "midterm": 70 });
query:
db.students.aggregate([ { $project: { quiztotal: { $sum: "$quizzes"}, labtotal: { $sum: "$labs" }, examtotal: { $sum: [ "$final", "$midterm" ] } } } ])
result memntioned in docs:
{ "_id" : 1, "quiztotal" : 23, "labtotal" : 13, "examtotal" : 155 } { "_id" : 2, "quiztotal" : 19, "labtotal" : 16, "examtotal" : 175 } { "_id" : 3, "quiztotal" : 14, "labtotal" : 11, "examtotal" : 148 }
acutal result:
assert: command failed: { "errmsg" : "exception: invalid operator '$sum'", "code" : 15999, "ok" : 0 } : aggregate failed error: command failed: { "errmsg" : "exception: invalid operator '$sum'", "code" : 15999, "ok" : 0 } : aggregate failed @ error (<anonymous>) @ doassert (src/mongo/shell/assert.js:11:14) @ function.assert.commandworked (src/mongo/shell/assert.js:254:5) @ dbcollection.aggregate (src/mongo/shell/collection.js:1278:12) @ (shell):1:13 2016-02-06t09:58:49.230+0530 e query error: command failed: { "errmsg" : "exception: invalid operator '$sum'", "code" : 15999, "ok" : 0 } : aggregate failed @ error (<anonymous>) @ doassert (src/mongo/shell/assert.js:11:14) @ function.assert.commandworked (src/mongo/shell/assert.js:254:5) @ dbcollection.aggregate (src/mongo/shell/collection.js:1278:12) @ (shell):1:13 @ src/mongo/shell/assert.js:13 >
Comments
Post a Comment