您可以使用聚合框架。让我们首先创建一个包含文档的集合 -
> 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 }