对于组查询,请使用MongoDB $group并使用$sum获取计数。让我们创建一个包含文档的集合-
> db.demo676.insertOne({"Marks":87}); { "acknowledged" : true, "insertedId" : ObjectId("5ea41eed04263e90dac943f2") } > db.demo676.insertOne({"Marks":75}); { "acknowledged" : true, "insertedId" : ObjectId("5ea41ef304263e90dac943f3") } > db.demo676.insertOne({"Marks":87}); { "acknowledged" : true, "insertedId" : ObjectId("5ea41ef404263e90dac943f4") } > db.demo676.insertOne({"Marks":65}); { "acknowledged" : true, "insertedId" : ObjectId("5ea41ef704263e90dac943f5") } > db.demo676.insertOne({"Marks":65}); { "acknowledged" : true, "insertedId" : ObjectId("5ea41ef804263e90dac943f6") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo676.find();
这将产生以下输出-
{ "_id" : ObjectId("5ea41eed04263e90dac943f2"), "Marks" : 87 } { "_id" : ObjectId("5ea41ef304263e90dac943f3"), "Marks" : 75 } { "_id" : ObjectId("5ea41ef404263e90dac943f4"), "Marks" : 87 } { "_id" : ObjectId("5ea41ef704263e90dac943f5"), "Marks" : 65 } { "_id" : ObjectId("5ea41ef804263e90dac943f6"), "Marks" : 65 }
以下是获取重复标记计数的查询-
> db.demo676.aggregate( { $group: { ... _id: {Marks: "$Marks" }, ... 'Count': { $sum :1 } ... }})
这将产生以下输出-
{ "_id" : { "Marks" : 75 }, "Count" : 1 } { "_id" : { "Marks" : 65 }, "Count" : 2 } { "_id" : { "Marks" : 87 }, "Count" : 2 }