php - 在 PHP 中使用 _id 查询 Mongo 日期范围

标签 php mongodb

对 mongo 比较陌生,我在 mongo 手册中阅读了有关优化对象 ID 的内容。

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

根据关于不创建单独的 Created_On 字段的建议,我决定稍后从 _id 字段中提取日期,该字段是一个 ObjectID

现在,我有很多记录都没有 Created_On 字段。

我正在尝试查询日期范围,但不确定语法:

$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)));

总是返回 0 个结果。虽然我可以查询单个记录并从对象中提取日期。

最佳答案

在 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))));

然后你可以用它来查询_id字段。

我在这里写了一篇描述该过程的博客文章:http://www.snailinaturtleneck.com/blog/2011/12/20/querying-for-timestamps-using-objectids/

关于php - 在 PHP 中使用 _id 查询 Mongo 日期范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9776980/

相关文章:

PHP is_numeric - 当指数在字符串中时为 false

PHPStorm 和 CodeIgniter 路由问题

javascript - 在 mongo 映射或减少上下文中调用外部 javascript 函数(对象)的可能方法

linux - Docker-compose - mongodb 无法通过身份验证

mongodb - 在mac中安装mongo shell

php - CodeIgniter Active Record 的批处理 "replace into"

php - 使用PHP检查用户名是否存在于MySQL表中?

c# - MongoDB:处理游标

php - 在 Ubuntu 服务器上安装 XHProf

javascript - 如何使用 KnockoutJS 数据绑定(bind)将使用 GridFS 上传的文件的信息显示到表中