要计算基于数组的字段中的唯一项,请使用$group和aggregate()
。让我们创建一个包含文档的集合-
> db.demo493.insertOne({"SubjectName":["MySQL","MongoDB","Java"]});{ "acknowledged" : true, "insertedId" : ObjectId("5e849f97b0f3fa88e22790c4") } > db.demo493.insertOne({"SubjectName":["C++","MongoDB","C"]});{ "acknowledged" : true, "insertedId" : ObjectId("5e849fa4b0f3fa88e22790c5") } > db.demo493.insertOne({"SubjectName":["MySQL","MongoDB","C"]});{ "acknowledged" : true, "insertedId" : ObjectId("5e849fb2b0f3fa88e22790c6") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo493.find();
这将产生以下输出-
{ "_id" : ObjectId("5e849f97b0f3fa88e22790c4"), "SubjectName" : [ "MySQL", "MongoDB", "Java" ] } { "_id" : ObjectId("5e849fa4b0f3fa88e22790c5"), "SubjectName" : [ "C++", "MongoDB", "C" ] } { "_id" : ObjectId("5e849fb2b0f3fa88e22790c6"), "SubjectName" : [ "MySQL", "MongoDB", "C" ] }
以下是查询所有文档中基于数组的字段中的唯一项的查询-
> db.demo493.aggregate([ ... { $unwind: "$SubjectName" }, ... { $group: { _id: "$SubjectName", Frequency: { $sum : 1 } } } ... ] ... );
这将产生以下输出-
{ "_id" : "C++", "Frequency" : 1 } { "_id" : "C", "Frequency" : 2 } { "_id" : "Java", "Frequency" : 1 } { "_id" : "MySQL", "Frequency" : 2 } { "_id" : "MongoDB", "Frequency" : 3 }