👨🏻💻 热爱摄影的程序员
👨🏻🎨 喜欢编码的设计师
🧕🏻 擅长设计的剪辑师
🧑🏻🏫 一位高冷无情的编码爱好者
大家好,我是 DevOps 工程师
欢迎分享 / 收藏 / 赞 / 在看!
【需求】查询创建时间在本月之内的记录
【解决】首先,数据中 create_date 字段存储时间戳,注意是13位,如果是其他位数要经过转换,否则查询结果对不上。
[{
"type": 1,
"create_date": 16828704000000, // 2503-4-14 0:0:0
"user_id": "0ce2",
"comment": "芭蕾舞课程到课"
},{
"type": 1,
"create_date": 1682872200000, // 2023-5-1 0:30:0
"user_id": "0ce2",
"comment": "拉丁舞课程到课"
},{
"type": 1,
"create_date": 1682874000000, // 2023-5-1 1:0:0
"user_id": "0ce2",
"comment": "芭蕾舞课程到课"
}]
其次,使用查询语句获取数据。
const currentDate = new Date() // Mon May 01 2023 02:00:51 GMT+0800 (中国标准时间)
const year = currentDate.getFullYear() // 2023
const month = currentDate.getMonth() // 4
const firstDayOfMonth = new Date(year, month, 1) // Mon May 01 2023 00:00:00 GMT+0800 (中国标准时间)
const lastDayOfMonth = new Date(year, month + 1, 0) // Wed May 31 2023 00:00:00 GMT+0800 (中国标准时间)
db.collection('your-collection').where({
user_id: '0ce2',
create_date: db.command.gte(firstDayOfMonth.getTime()).and(db.command.lte(lastDayOfMonth
.getTime()))
}).get()
最终结果:
[
{
"_id": "9d7d",
"comment": "拉丁舞课程到课",
"create_date": 1682872200000,
"type": 1,
"user_id": "0ce2"
},
{
"_id": "eb87",
"comment": "芭蕾舞课程到课",
"create_date": 1682874000000,
"type": 1,
"user_id": "0ce2"
}
]