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

Truy vấn MongoDB group by _id

Để nhóm theo _id trong MongoDB, sử dụng $group với _id: null để gom tất cả tài liệu thành một nhóm. Tạo collection:

> db.demo529.insertOne({"Score":10});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8b1d5bef4dcbee04fbbbe4") }
> db.demo529.insertOne({"Score":20});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8b1d5fef4dcbee04fbbbe5") }
> db.demo529.insertOne({"Score":10});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8b1d61ef4dcbee04fbbbe6") }
> db.demo529.insertOne({"Score":10});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8b1d62ef4dcbee04fbbbe7") }

Hiển thị dữ liệu (4 tài liệu, Score: 10, 20, 10, 10):

> db.demo529.find();

Kết quả:

Group by _id null để đếm tổng số tài liệu:

> db.demo529.aggregate([
  { $group: { _id: null, count: { $sum: 1 } } }
])

Kết quả trả về 1 tài liệu với count=4:

Giải thích: _id: null nghĩa là không nhóm theo trường nào, gom tất cả vào 1 nhóm. $sum: 1 đếm mỗi tài liệu là 1. Đây là cách đếm tổng số document trong collection (tương đương countDocuments()).

Mở rộng: Group theo trường cụ thể: { $group: { _id: "$Score", count: { $sum: 1 } } } sẽ cho: Score 10 → count 3, Score 20 → count 1.