问题
I have a document as Follows:
{_id:1,"$field1":10,"$field2":20}
Through mongo db java driver, can we update all the documents with a new field called $total which would sum of field1 and field2
THe equivalent in Relation database would like
Update table set total=field1+field2
Is the same possible using mongo DB java driver without fetching records one by one.
I have tried the following link and it doesnt give the result as specified in the 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 the 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
at Error (<anonymous>)
at doassert (src/mongo/shell/assert.js:11:14)
at Function.assert.commandWorked (src/mongo/shell/assert.js:254:5)
at DBCollection.aggregate (src/mongo/shell/collection.js:1278:12)
at (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
at Error (<anonymous>)
at doassert (src/mongo/shell/assert.js:11:14)
at Function.assert.commandWorked (src/mongo/shell/assert.js:254:5)
at DBCollection.aggregate (src/mongo/shell/collection.js:1278:12)
at (shell):1:13 at src/mongo/shell/assert.js:13
>
来源:https://stackoverflow.com/questions/35237254/sum-using-mongo-db-aggreagation