我正在尝试根据它们的创建时间获取特定范围的文档。我想要做的是:
用户可以根据所选月份浏览所有记录。
在我的数据库中,我没有存储created_at日期,但我知道mongodb将它存储在objectid中。
我发现我可以得到这样的记录:
db.claims.find({
$where: function () { return Date.now() - this._id.getTimestamp() < (365 * 24 * 60 * 60 * 1000) }
})
当然不会根据特定月份进行过滤,但仅限于特定时限内。
使用来自objectid的时间戳,基于特定月份限制查询的可能方法是什么?
我正在使用mongoose,但从mongo shell本身开始可能是一个好主意。
感谢您的帮助!
答案 0 :(得分:1)
基于从这个问题的答案借来的功能 - https://stackoverflow.com/a/8753670/131809
function objectIdWithTimestamp(timestamp) {
// Convert date object to hex seconds since Unix epoch
var hexSeconds = Math.floor(timestamp/1000).toString(16);
// Create an ObjectId with that hex timestamp
return ObjectId(hexSeconds + "0000000000000000");
}
为您正在寻找的月份创建开始日期和结束日期:
var start = objectIdWithTimestamp(new Date(2015, 01, 01));
var end = objectIdWithTimestamp(new Date(2015, 01, 31));
然后,使用$gte
和$lt
:
db.claims.find({_id: {$gte: start, $lt: end}});