包含多个键的 MongoDB 聚合
若要执行包含多个键的聚合,请将 aggregate() 与 $group 结合使用。让我们使用文档创建集合 −
> db.demo190.insertOne( ... { ... ... "DueDate" : ISODate("2020-01-01"), ... "Value" : 10, ... "Name" : "Chris" ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5e3ad76403d395bdc21346bf") } > > db.demo190.insertOne( ... { ... ... "DueDate" : ISODate("2020-02-05"), ... "Value" : 30, ... "Name" : "David" ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5e3ad76403d395bdc21346c0") } > db.demo190.insertOne( ... { ... ... "DueDate" : ISODate("2020-01-01"), ... "Value" : 40, ... "Name" : "Chris" ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5e3ad7f003d395bdc21346c1") }
使用 find() 方法从集合中显示所有文档 −
> db.demo190.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e3ad76403d395bdc21346bf"), "DueDate" : ISODate("2020-01-01T00:00:00Z"), "Value" : 10, "Name" : "Chris" } { "_id" : ObjectId("5e3ad76403d395bdc21346c0"), "DueDate" : ISODate("2020-02-05T00:00:00Z"), "Value" : 30, "Name" : "David" } { "_id" : ObjectId("5e3ad7f003d395bdc21346c1"), "DueDate" : ISODate("2020-01-01T00:00:00Z"), "Value" : 40, "Name" : "Chris" }
以下是使用多个键执行 MongoDB 聚合的查询 −
> db.demo190.aggregate( [ { "$group": { "_id": { "Name": "$Name", "DueDate": { "$year": "$DueDate" } }, "Value": { "$sum": "$Value" } } } ], function(err,results) { console.log(results); } );
这将产生以下输出 −
{ "_id" : { "Name" : "David", "DueDate" : 2020 }, "Value" : 30 } { "_id" : { "Name" : "Chris", "DueDate" : 2020 }, "Value" : 50 }
广告