累加器是运算符,可在文档通过管道前进时保持其状态。
$ROOT引用当前在聚合管道阶段正在处理的根文档,即顶级文档。
让我们创建一个包含文档的集合-
> db.demo582.insertOne({FirstName:"Chris",Age:21,createDate:new ISODate("2020-01-10")});{ "acknowledged" : true, "insertedId" : ObjectId("5e91ce41fd2d90c177b5bcbd") } > db.demo582.insertOne({FirstName:"Chris",Age:21,createDate:new ISODate("2020-04-21")});{ "acknowledged" : true, "insertedId" : ObjectId("5e91ce4ffd2d90c177b5bcbe") } > db.demo582.insertOne({FirstName:"Chris",Age:22,createDate:new ISODate("2020-02-11")});{ "acknowledged" : true, "insertedId" : ObjectId("5e91ce59fd2d90c177b5bcbf") } > db.demo582.insertOne({FirstName:"Chris",Age:22,createDate:new ISODate("2020-01-12")});{ "acknowledged" : true, "insertedId" : ObjectId("5e91ce6efd2d90c177b5bcc0") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo582.find();
这将产生以下输出-
{ "_id" : ObjectId("5e91ce41fd2d90c177b5bcbd"), "FirstName" : "Chris", "Age" : 21, "createDate" : ISODate("2020-01-10T00:00:00Z") } { "_id" : ObjectId("5e91ce4ffd2d90c177b5bcbe"), "FirstName" : "Chris", "Age" : 21, "createDate" : ISODate("2020-04-21T00:00:00Z") } { "_id" : ObjectId("5e91ce59fd2d90c177b5bcbf"), "FirstName" : "Chris", "Age" : 22, "createDate" : ISODate("2020-02-11T00:00:00Z") } { "_id" : ObjectId("5e91ce6efd2d90c177b5bcc0"), "FirstName" : "Chris", "Age" : 22, "createDate" : ISODate("2020-01-12T00:00:00Z") }
以下是应用Group Accumulator运算符的查询-
> db.demo582.aggregate([ ... { ... "$group": { ... "_id": "$FirstName", ... "MaximumDate": { ... "$max": "$createDate" ... }, ... "count": { ... "$sum": 1 ... }, ... "details": { ... "$first": "$$ROOT" ... } ... } ... }, ... { ... "$project": { ... "MaximumDate": 1, ... "count": 1, ... "details": { ... "_id": "$_id", ... "FirstName": "$details.FirstName", ... "Age" : "$details.Age", ... } ... } ... } ... ])
这将产生以下输出-
{ "_id" : "Chris", "MaximumDate" : ISODate("2020-04-21T00:00:00Z"), "count" : 4, "details" : { "_id" : "Chris", "FirstName" : "Chris", "Age" : 21 } }