Sử dụng aggregate() với $filter, $size, $group, $sort và $limit để tìm tài liệu có số lần xuất hiện nhiều nhất của giá trị 65.
Tạo collection:
> 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") }
Hiển thị dữ liệu (bản ghi 1: 65 xuất hiện 2 lần, bản ghi 2: 65 xuất hiện 5 lần):
> 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 ] }
Pipeline phức tạp: $project đếm số lần 65 xuất hiện, $group theo count, $sort giảm dần, $limit 1:
> 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 }
...]);
Kết quả trả về tài liệu có 5 lần xuất hiện giá trị 65:
{ "_id" : 5, "MyValues" : [ { "_id" : ObjectId("5e06efaa25ddae1f53b621ec"), "ListOfValues" : [ 102, 65, 87, 65, 89, 65, 89, 65, 89, 65 ], "OccurencesValue" : 5 } ] }