Để nhóm tài liệu theo ngày (ngày/tháng/năm), sử dụng $group kết hợp các toán tử ngày trong aggregation. Tạo collection:
> db.demo657.insertOne({ id: 1, Name: "Chris", DueDate: new ISODate("2020-04-22") });
{ "acknowledged" : true, "insertedId" : ObjectId("5ea064b44deddd72997713d6") }
> db.demo657.insertOne({ id: 1, Name: "John", DueDate: new ISODate("2020-04-22") });
{ "acknowledged" : true, "insertedId" : ObjectId("5ea064b44deddd72997713d7") }
> db.demo657.insertOne({ id: 1, Name: "Chris", DueDate: new ISODate("2020-04-22") });
{ "acknowledged" : true, "insertedId" : ObjectId("5ea064b44deddd72997713d8") }
Hiển thị dữ liệu (3 tài liệu cùng ngày 22/04/2020):
> db.demo657.find();
Kết quả:
Pipeline:
$matchlọc id=1 và DueDate trong khoảng 21/04 đến 23/04,$projecttrích xuất day/month/year,$groupnhóm theo ngày/tháng/năm, push tên vào mảng:> db.demo657.aggregate([ {$match: {id:1, DueDate: {$gte:new ISODate('2020-04-21'), $lt:new ISODate("2020-04-23")}}}, {$project: {day: {'$dayOfMonth': '$DueDate'}, month: {'$month':'$DueDate'}, year: {'$year':'$DueDate'}, Name: "$Name" }}, {$group: { _id: {day:'$day',month:'$month',year:'$year'}, ListOfNames: {$push:{Name:'$Name'}} }} ])Kết quả nhóm theo 22/04/2020 với 3 tên:
Các toán tử ngày hữu ích:
$dayOfMonth,$month,$year,$dayOfWeek,$dayOfYear,$week,$isoWeek,$hour,$minute,$second,$millisecond.Mẹo: Để nhóm theo ngày đơn giản hơn, dùng
$dateToString:{ $dateToString: { format: "%Y-%m-%d", date: "$DueDate" } }làm _id nhóm.