MongoDB 查询利用聚合框架分组若干字段?
如需分组多个字段,可在 MongoDB 中使用 $group。我们使用文档创建一个集合 −
> db.demo192.insertOne({"Name":"Chris","Age":22}); { "acknowledged" : true, "insertedId" : ObjectId("5e3adb9f03d395bdc21346cd") } > db.demo192.insertOne({"Name":"David","Age":21}); { "acknowledged" : true, "insertedId" : ObjectId("5e3adba103d395bdc21346ce") } > db.demo192.insertOne({"Name":"Chris","Age":22}); { "acknowledged" : true, "insertedId" : ObjectId("5e3adba503d395bdc21346cf") } > db.demo192.insertOne({"Name":"Mike","Age":24}); { "acknowledged" : true, "insertedId" : ObjectId("5e3adbbf03d395bdc21346d0") }
利用 find() 方法显示集合中的所有文档 −
> db.demo192.find();
将生成以下输出 −
{ "_id" : ObjectId("5e3adb9f03d395bdc21346cd"), "Name" : "Chris", "Age" : 22 } { "_id" : ObjectId("5e3adba103d395bdc21346ce"), "Name" : "David", "Age" : 21 } { "_id" : ObjectId("5e3adba503d395bdc21346cf"), "Name" : "Chris", "Age" : 22 } { "_id" : ObjectId("5e3adbbf03d395bdc21346d0"), "Name" : "Mike", "Age" : 24 }
以下是使用聚合框架对几个字段进行分组的查询 −
> db.demo192.aggregate([{$group:{_id:{Age:"$Age",Name:"$Name"}}}]);
将生成以下输出 −
{ "_id" : { "Age" : 24, "Name" : "Mike" } } { "_id" : { "Age" : 21, "Name" : "David" } } { "_id" : { "Age" : 22, "Name" : "Chris" } }
广告