MongoDB查询来计算数组中每个元素的频率(出现次数)
要进行计数,您还可以将aggregate()与$sum一起使用。让我们创建一个包含文档的集合-
> db.demo184.insertOne({"Names":["Chris","David","Bob"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3999fb9e4f06af55199805") } > db.demo184.insertOne({"Names":["Chris","Mike"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e399a0d9e4f06af55199806") } > db.demo184.insertOne({"Names":["Chris","Bob","Carol"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e399a209e4f06af55199807") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo184.find();
这将产生以下输出-
{ "_id" : ObjectId("5e3999fb9e4f06af55199805"), "Names" : [ "Chris", "David", "Bob" ] } { "_id" : ObjectId("5e399a0d9e4f06af55199806"), "Names" : [ "Chris", "Mike" ] } { "_id" : ObjectId("5e399a209e4f06af55199807"), "Names" : [ "Chris", "Bob", "Carol" ] }
以下是查询以计算每个元素的频率-
> db.demo184.aggregate([ ... { "$unwind" : "$Names" }, ... { "$group": { "_id": "$Names", "count": { "$sum": 1} } }, ... { "$group": { ... "_id": null, ... "counts": { ... "$push": { ... "k": "$_id", ... "v": "$count" ... } ... } ... } }, ... { "$replaceRoot": { ... "newRoot": { "$arrayToObject": "$counts" } ... } } ...])
这将产生以下输出-
{ "Carol" : 1, "David" : 1, "Chris" : 3, "Bob" : 2, "Mike" : 1 }