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

Đếm số lần xuất hiện giá trị cụ thể trong MongoDB

Để đếm số lần xuất hiện giá trị cụ thể trong mảng, sử dụng aggregate() với $unwind và $group. Tạo collection:

> db.demo210.insertOne({
   details: [
      { ClientName: "Robert" },
      { ClientName: "John Doe" },
      { ClientName: "Robert" },
      { ClientName: "Robert" },
      { ClientName: "David Miller" }
   ]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3d99ab03d395bdc21346f9") }

Hiển thị tài liệu:

> db.demo210.find();

Kết quả - Robert xuất hiện 3 lần:

Aggregation pipeline đếm số lần "Robert" xuất hiện:

> db.demo210.aggregate([
   { "$match" : { "details.ClientName" : "Robert" } },
   { "$unwind" : "$details" },
   { "$match" : { "details.ClientName" : "Robert" } },
   { "$group" : { "_id" : "$_id", "Size" : { "$sum" : 1 } } },
   { "$match" : { "Size" : { "$gte" : 2 } } }
]);

Kết quả - tài liệu có 3 lần "Robert":

Quy trình: 1) Lọc tài liệu chứa "Robert", 2) Unwind mảng details, 3) Lọc lại chỉ phần tử "Robert", 4) Group đếm số phần tử, 5) Lọc tài liệu có count >= 2.