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

NHÓM THEO mảng tài liệu để đếm số lần lặp lại giá trị Age

Để GROUP BY mảng tài liệu, hãy sử dụng $unwind tách mảng, sau đó $group theo trường Age và $sort.

Tạo collection với mảng details chứa các object Name, Age:

>db.demo559.insertOne({details:[{Name:"Chris",Age:21},{Name:"Bob",Age:22},{Name:"Carol", Age:21},{Name:"Sam",Age:21}]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8f38d954b4472ed3e8e866") }

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

> db.demo559.find().pretty();

Kết quả (1 tài liệu chứa mảng 4 phần tử):

{
    "_id" : ObjectId("5e8f38d954b4472ed3e8e866"),
    "details" : [
        { "Name" : "Chris", "Age" : 21 },
        { "Name" : "Bob", "Age" : 22 },
        { "Name" : "Carol", "Age" : 21 },
        { "Name" : "Sam", "Age" : 21 }
    ]
}

Aggregate: unwind details, group theo details.Age đếm Count, sort theo _id (Age):

> db.demo559.aggregate([
...     { "$unwind": "$details" },
...     { "$group": { "_id": "$details.Age", "Count": { "$sum" : 1 } } },
...     { "$sort": { "_id" : 1 } }
... ])

Kết quả (Age 21: 3 lần, Age 22: 1 lần):

{ "_id" : 21, "Count" : 3 }
{ "_id" : 22, "Count" : 1 }