Để truy vấn document theo tháng hoặc năm cụ thể từ trường ngày tháng (ISODate) trong MongoDB, bạn sử dụng Aggregation Framework với toán tử projection $month hoặc $year.
Tạo dữ liệu mẫu
> db.specificMonthDemo.insertOne({"StudentName":"Larry","StudentDateOfBirth":new ISODate('1995-01-12')});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb9a9ca8f1d1b97daf71819") }
> db.specificMonthDemo.insertOne({"StudentName":"Chris","StudentDateOfBirth":new ISODate('1999-12-31')});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb9a9db8f1d1b97daf7181a") }
> db.specificMonthDemo.insertOne({"StudentName":"David","StudentDateOfBirth":new ISODate('2000-06-01')});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb9a9ee8f1d1b97daf7181b") }
Hiển thị document:
> db.specificMonthDemo.find().pretty();
Truy vấn sinh viên sinh tháng 1 (January)
> db.specificMonthDemo.aggregate([ {$project: {StudentName: 1, StudentDateOfBirth: {$month: '$StudentDateOfBirth'}}}, {$match: {StudentDateOfBirth: 1}} ]).pretty();Kết quả:
Các toán tử ngày tháng hữu ích
$year- Trả về năm (ví dụ: 1995)$month- Trả về tháng (1-12)$dayOfMonth- Ngày trong tháng (1-31)$dayOfWeek- Thứ trong tuần (1=Chủ nhật, 7=Thứ bảy)$week- Tuần trong năm (0-53)
Mẹo: Để lọc trực tiếp trong query (không dùng aggregation), hãy dùng range query: {date: {$gte: ISODate("2024-01-01"), $lt: ISODate("2024-02-01")}} cho tháng 1/2024 - cách này tận dụng index hiệu quả hơn.