为此,您可以使用aggregate()
。首先让我们创建一个包含文档的集合-
> db.countOccurrencesDemo.insertOne({"ListOfValues":[65,87,89,65,67,87,87,87]}); { "acknowledged" : true, "insertedId" : ObjectId("5e06ef9325ddae1f53b621eb") } > db.countOccurrencesDemo.insertOne({"ListOfValues":[102,65,87,65,89,65,89,65,89,65]}); { "acknowledged" : true, "insertedId" : ObjectId("5e06efaa25ddae1f53b621ec") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.countOccurrencesDemo.find();
这将产生以下输出-
{ "_id" : ObjectId("5e06ef9325ddae1f53b621eb"), "ListOfValues" : [ 65, 87, 89, 65, 67, 87, 87, 87 ] } { "_id" : ObjectId("5e06efaa25ddae1f53b621ec"), "ListOfValues" : [ 102, 65, 87, 65, 89, 65, 89, 65, 89, 65 ] }
这是查找包含最大出现特定值的数组的文档的查询-
> db.countOccurrencesDemo.aggregate( ... [ ... { "$project": { ... "ListOfValues": 1, ... "OccurencesValue": { ... "$size": { ... "$filter": { ... "input": "$ListOfValues", ... "as": "v", ... "cond": { "$eq": [ "$$v", 65] } ... } ... } ... } ... }}, ... { "$group": { ... "_id": "$OccurencesValue", ... "MyValues": { "$push": "$$ROOT" } ... }}, ... { "$sort": { "_id": -1 } }, ... { "$limit": 1 } ... ] ... );
这将产生以下输出-
{ "_id" : 5, "MyValues" : [ { "_id" : ObjectId("5e06efaa25ddae1f53b621ec"), "ListOfValues" : [ 102, 65, 87, 65, 89, 65, 89, 65, 89, 65 ], "OccurencesValue" : 5 } ] }