将_id用于日期查询条件

时间:2015-07-09 06:13:44

标签: javascript mongodb mongodb-query

我知道_id字段可以转换为日期 这是功能:

ObjectId.prototype.getTimestamp = function() {
  return new Date(parseInt(this.toString().slice(0,8), 16)*1000);
}

然后我可以使用doc._id.getTimestamp();来显示文档的创建日期时间。

问题是,该文档只有与日期相关的_id字段。 我的问题是:如何仅通过_id查询特定日期范围的文档?

2 个答案:

答案 0 :(得分:3)

您可以使用$where将JavaScript发送到服务器以进行查询。但是忘记原型,因为所有逻辑必须是自包含的或以其他方式加载到服务器上。这意味着必须在函数中进行评估:

db.collection.find(function() {
    return 
        ( new Date(parseInt(this._id.toString().slice(0,8), 16)*1000)
           > new Date("2015-01-01") ) &&
        ( new Date(parseInt(this._id.toString().slice(0,8), 16)*1000)
           < new Date("2015-02-01") );
})

但这不是一个好主意,因为$where无法使用“索引”来过滤匹配。

您最好使用实际日期对象创建“时间戳”字段,并使用$lt$gt运算符本身。可以对该实际字段编制索引,操作员将使用该字段进行选择。

另一种方法是计算查询之外的ObjectId值,然后使用标准运算符:

var start =  ObjectId(
    (new Date("2015-01-01").valueOf() / 1000).toString(16) + "0000000000000000")
 ),
    end =  ObjectId(
     (new Date("2015-02-01").valueOf() / 1000).toString(16) + "0000000000000000")
 );

db.collection.find({ "_id": { "$gt": start, "$lt": end } })

从日期创建ObjectId值,并允许您使用始终存在的主键索引。

有些驱动程序甚至在ObjectId实现上支持“从时间戳创建”方法。

答案 1 :(得分:0)

function GetTimeID(yourTime){
    yourTime = new Date(yourTime);
    yourTime = Math.floor(yourTime/1000).toString(16);
    var newID = ObjectId(yourTime + "0000000000000000");
    return newID;
}

var firstDateID = GetTimeID("1/1/2015");
var secondDateID = GetTimeID("1/1/2015");

var batList = batmanCollection.find({_id: {$gt: firstDateID }}).toArray();

var batList = batmanCollection.find({_id: {$lt: secondDateID }}).toArray();

var batList = batmanCollection
    .find({_id: {$lt: firstDateID , $gt: secondDateID }}).toArray();