为此,请在MongoDB聚合中使用$group。让我们创建一个包含文档的集合-
> db.demo639.insertOne( ... { ... "_id" : 1, ... "CountryName" : "US", ... "Info1" : { ... "Name" : "Chris", ... "SubjectName" : "MySQL", ... "Marks" : 78 ... }, ... "Info2" : { ... "Name" : "Chris", ... "SubjectName" : "MySQL", ... "Marks" : 78 ... } ... } ... ); { "acknowledged" : true, "insertedId" : 1 } > db.demo639.insertOne( ... { ... "_id" : 2, ... "CountryName" : "UK", ... "Info1" : { ... "Name" : "Chris", ... "SubjectName" : "MySQL", ... "Marks" : 79 ... }, ... "Info2" : { ... "Name" : "Chris", ... "SubjectName" : "MySQL", ... "Marks" : 88 ... } ... } ... ); { "acknowledged" : true, "insertedId" : 2 }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo639.find();
这将产生以下输出-
{ "_id" : 1, "CountryName" : "US", "Info1" : { "Name" : "Chris", "SubjectName" : "MySQL", "Marks" : 78 }, "Info2" : { "Name" : "Chris", "SubjectName" : "MySQL", "Marks" : 78 } } { "_id" : 2, "CountryName" : "UK", "Info1" : { "Name" : "Chris", "SubjectName" : "MySQL", "Marks" : 79 }, "Info2" : { "Name" : "Chris", "SubjectName" : "MySQL", "Marks" : 88 } }
以下是使用$group查询的聚合框架查询-
> db.demo639.aggregate({$group : {_id : {Name1:"$Info1.Name",Name2:"$Info2.Name"}, ... ... Marks:{$first:"$Info2.Marks"}, ... Marks:{$sum:"$Info2.Marks"} ... }}).pretty();
这将产生以下输出-
{ "_id" : { "Name1" : "Chris", "Name2" : "Chris" }, "Marks" : 166 }