我有一份文件如下:
{_ ID:1" $ FIELD1":10," $ FIELD2" 20}
通过mongo db java驱动程序,我们可以使用名为$ total的新字段更新所有文档,该字段将是field1和field2的总和
在Relation数据库中的等价物
更新表格总计=字段1 +字段2
使用mongo DB java驱动程序可以逐个获取记录。
我尝试了以下链接,但它没有给出链接
中指定的结果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 });
查询:
db.students.aggregate([
{
$project: {
quizTotal: { $sum: "$quizzes"},
labTotal: { $sum: "$labs" },
examTotal: { $sum: [ "$final", "$midterm" ] }
}
}
])
文档中记载的结果:
{ "_id" : 1, "quizTotal" : 23, "labTotal" : 13, "examTotal" : 155 }
{ "_id" : 2, "quizTotal" : 19, "labTotal" : 16, "examTotal" : 175 }
{ "_id" : 3, "quizTotal" : 14, "labTotal" : 11, "examTotal" : 148 }
实际结果:
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
>