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 }
广告