Bạn có thể sử dụng khung tổng hợp cùng với toán tử dự báo $ month. Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệ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")
} Sau đây là truy vấn để hiển thị tất cả các tài liệu từ bộ sưu tập với sự trợ giúp của phương thức find () -
> db.specificMonthDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5cb9a9ca8f1d1b97daf71819"),
"StudentName" : "Larry",
"StudentDateOfBirth" : ISODate("1995-01-12T00:00:00Z")
}
{
"_id" : ObjectId("5cb9a9db8f1d1b97daf7181a"),
"StudentName" : "Chris",
"StudentDateOfBirth" : ISODate("1999-12-31T00:00:00Z")
}
{
"_id" : ObjectId("5cb9a9ee8f1d1b97daf7181b"),
"StudentName" : "David",
"StudentDateOfBirth" : ISODate("2000-06-01T00:00:00Z")
} Sau đây là truy vấn để lấy tháng | năm cụ thể, không phải ngày -
> db.specificMonthDemo.aggregate([ {$project: {StudentName: 1, StudentDateOfBirth:
{$month: '$StudentDateOfBirth'}}}, {$match: {StudentDateOfBirth: 01}} ]).pretty(); Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5cb9a9ca8f1d1b97daf71819"),
"StudentName" : "Larry",
"StudentDateOfBirth" : 1
}