简体   繁体   English

使用PHP中的_id进行Mongo日期范围查询

[英]Mongo date range query using _id in PHP

Being relatively new to mongo, I read in the mongo manual about Optimizing Object IDs. 作为mongo的新手,我在mongo手册中读到了有关优化对象ID的信息。

http://www.mongodb.org/display/DOCS/Optimizing+Object+IDs#OptimizingObjectIDs-Extractinsertiontimesfromidratherthanhavingaseparatetimestampfield . http://www.mongodb.org/display/DOCS/Optimizing+Object+IDs#OptimizingObjectIDs-Extractinsertiontimesfromntratherthanhavingaseparatetimestampfield

Going with the recommendation about NOT creating a separate Created_On field, I decided I would later extract out the date from the _id field which is an ObjectID 根据关于不创建单独的Created_On字段的建议,我决定稍后从_id字段中提取日期,这是一个ObjectID

Now, I have many records all with out a Created_On field. 现在,我有很多记录都没有Created_On字段。

I am attempting to query for a date range, but am unsure of the syntax: 我试图查询日期范围,但不确定语法:

$start = new MongoDate(strtotime("2012-03-01 00:00:00"));
$end = new MongoDate(strtotime("2012-03-15 00:00:00"));

$collection->find(array('_id' => array('$gt' => $start, '$lte' => $end)));

Always returns 0 results. 始终返回0结果。 Although I can query individual records and extract the date from the object. 虽然我可以查询单个记录并从对象中提取日期。

In PHP, you need to do something like: 在PHP中,您需要执行以下操作:

function timeToId($ts) {
    // turn it into hex
    $hexTs = dechex($ts);
    // pad it out to 8 chars
    $hexTs = str_pad($hexTs, 8, "0", STR_PAD_LEFT);
    // make an _id from it
    return new MongoId($hexTs."0000000000000000");
}

$start = strtotime("2012-03-01 00:00:00");
$end = strtotime("2012-03-15 00:00:00");

$collection->find(array('_id' => array('$gt' => timeToId($start), '$lte' => timeToId($end))));

Then you can use that to query the _id field. 然后,您可以使用它来查询_id字段。

I wrote a blog post describing the process here: http://www.snailinaturtleneck.com/blog/2011/12/20/querying-for-timestamps-using-objectids/ 我在这里写了一篇描述这个过程的博客文章: http//www.snailinaturtleneck.com/blog/2011/12/20/querying-for-timestamps-using-objectids/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM