如何在mongodb中按特定月份查找数据
{
"_id" : ObjectId("5a4212b49e710765c486d7c6"),
"student_id" : ObjectId("5a3df85bcc6425291c54d2ad"),
"attendance_status" : true,
"create_at" : 1514279592137.0,
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("5a4212b49e710765c486d7c7"),
"student_id" : ObjectId("5a3df85bcc6425291c54d2ae"),
"attendance_status" : true,
"create_at" : 1514279592137.0,
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("5a4212b49e710765c486d7c9"),
"student_id" : ObjectId("5a3df85bcc6425291c54d2b0"),
"attendance_status" : true,
"create_at" : 1514279592137.0,
"__v" : NumberInt(0)
}
我将创建时间存储为tramp。我想获得一个基于创建月份的数据来实现它?
我试图使用以下查询查找数据。
Attendance.aggregate(
[{
$project: {
create_at: "$create_at",
student_id: "$student_id",
attendance_status: "$attendance_status",
month: {
$month: "$create_at"
}
}
},
{
$match: {
"month": req.body.month
}
},
])
我想基于创建月份的输出。如果我发送req.body.month = 3.我只想在3个月内获得数据。
回答如下:无论您想要查询数据的月份,都可以通过使用new Date('YYYY-MM-DD').getTime()
and查询数据库获取开始时间戳和结束时间戳(e)
Attendance.find(
{
create_at: {
$gte: s, //$gte corresponds to >=
$lte: e //$lte corresponds to <=
}
}
)
您可以找到有关此类mongo运算符here的更多详细信息