Để nhóm, hãy sử dụng $ tuần và $ tháng trong MongoDB. Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> db.demo133.insertOne({"Rank":18,"DueDate":new ISODate("2020-01-10")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e31980968e7f832db1a7f78")
}
> db.demo133.insertOne({"Rank":12,"DueDate":new ISODate("2020-01-10")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e31982568e7f832db1a7f79")
}
> db.demo133.insertOne({"Rank":12,"DueDate":new ISODate("2020-02-01")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e31986568e7f832db1a7f7a")
}
> db.demo133.insertOne({"Rank":20,"DueDate":new ISODate("2020-02-01")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e31986c68e7f832db1a7f7b")
} Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -
> db.demo133.find();
Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5e31980968e7f832db1a7f78"), "Rank" : 18, "DueDate" : ISODate("2020-01-10T00:00:00Z") }
{ "_id" : ObjectId("5e31982568e7f832db1a7f79"), "Rank" : 12, "DueDate" : ISODate("2020-01-10T00:00:00Z") }
{ "_id" : ObjectId("5e31986568e7f832db1a7f7a"), "Rank" : 12, "DueDate" : ISODate("2020-02-01T00:00:00Z") }
{ "_id" : ObjectId("5e31986c68e7f832db1a7f7b"), "Rank" : 20, "DueDate" : ISODate("2020-02-01T00:00:00Z") } Sau đây là truy vấn để nhóm theo ngày / tháng / tuần dựa trên phạm vi ngày -
> db.demo133.aggregate([
... {
... "$project": {
... "DueDateWeek": { "$week": "$DueDate" },
... "DueDateMonth": { "$month": "$DueDate" },
... "Rank": 1
... }
... },
... {
... "$group": {
... "_id": "$DueDateWeek",
... "AvgValue": { "$avg": "$Rank" },
... "MonthValue": { "$first": "$DueDateMonth" }
... }
... }
... ]) Điều này sẽ tạo ra kết quả sau -
{ "_id" : 4, "AvgValue" : 16, "MonthValue" : 2 }
{ "_id" : 1, "AvgValue" : 15, "MonthValue" : 1 }