如何维护MongoDB中数组元素的最高计数?
可以使用聚合框架。让我们首先创建一个包含文档的集合 -
> db.topCountArrayDemo.insertOne( ... {"StudentId":101 , "StudentSubject": ["C", "MongoDB"]} ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cc6b3209cb58ca2b005e669") } > db.topCountArrayDemo.insertOne( ... {"StudentId":102 , "StudentSubject": ["C", "Java"]} ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cc6b3219cb58ca2b005e66a") } > db.topCountArrayDemo.insertOne( ... {"StudentId":103 , "StudentSubject": ["C", "MongoDB"]} ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cc6b3229cb58ca2b005e66b") }
以下是使用find()方法显示集合中所有文档的查询 -
> db.topCountArrayDemo.find().pretty();
这将产生以下输出 -
{ "_id" : ObjectId("5cc6b3209cb58ca2b005e669"), "StudentId" : 101, "StudentSubject" : [ "C", "MongoDB" ] } { "_id" : ObjectId("5cc6b3219cb58ca2b005e66a"), "StudentId" : 102, "StudentSubject" : [ "C", "Java" ] } { "_id" : ObjectId("5cc6b3229cb58ca2b005e66b"), "StudentId" : 103, "StudentSubject" : [ "C", "MongoDB" ] }
以下是维护MongoDB中数组元素最高计数的查询 -
> db.topCountArrayDemo.aggregate( ... [ ... { ... $unwind: "$StudentSubject" ... }, ... { ... $group: { ... _id: "$StudentSubject", ... Frequency: {$sum: 1} ... } ... }, ... { ... $sort: {Frequency:-1} ... }, ... { ... $limit: 2 ... } ... ] ... ).pretty();
这将产生以下输出 -
{ "_id" : "C", "Frequency" : 3 } { "_id" : "MongoDB", "Frequency" : 2 }
广告