Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Truy vấn MongoDB đếm tần suất xuất hiện của mỗi phần tử mảng

Sử dụng $unwind để tách mảng, sau đó $group với $sum để đếm, cuối cùng $replaceRoot + $arrayToObject để định dạng kết quả. Tạo collection:

> db.demo184.insertOne({ "Names": ["Chris", "David", "Bob"] });
{ "acknowledged": true, "insertedId": ObjectId("5e3999fb9e4f06af55199805") }
> db.demo184.insertOne({ "Names": ["Chris", "Mike"] });
{ "acknowledged": true, "insertedId": ObjectId("5e399a0d9e4f06af55199806") }
> db.demo184.insertOne({ "Names": ["Chris", "Bob", "Carol"] });
{ "acknowledged": true, "insertedId": ObjectId("5e399a209e4f06af55199807") }

Hiển thị document.

Pipeline aggregate:

> db.demo184.aggregate([
  { "$unwind": "$Names" },
  { "$group": { "_id": "$Names", "count": { "$sum": 1 } } },
  { "$group": {
    "_id": null,
    "counts": { "$push": { "k": "$_id", "v": "$count" } }
  }},
  { "$replaceRoot": { "newRoot": { "$arrayToObject": "$counts" } } }
])

Kết quả (tần suất mỗi tên):

{ "Carol": 1, "David": 1, "Chris": 3, "Bob": 2, "Mike": 1 }