查找包含出现次数最多的特定值数组的 MongoDB 文档
为此,你可以使用 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 } ] }
广告