使用 PHP 在 MongoDB 中插入和检索日期和时间戳,可以使用 MongoDB 的日期类型 MongoDB\BSON\UTCDateTime
。
首先,确保已经安装了 MongoDB PHP 驱动程序。可以使用 Composer 安装:
composer require mongodb/mongodb
然后,创建一个 PHP 文件,例如 mongodb_date.php
,并添加以下代码:
<?php
require 'vendor/autoload.php';
// 连接到 MongoDB
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
// 创建一个 UTCDateTime 对象
$datetime = new MongoDB\BSON\UTCDateTime();
// 插入一个包含日期和时间戳的文档
$bulk = new MongoDB\Driver\BulkWrite();
$bulk->insert([
"name" => "John",
"created_at" => $datetime,
"timestamp" => $datetime->toDateTime()->getTimestamp()
]);
$result = $manager->executeBulkWrite("test.users", $bulk);
// 查询刚刚插入的文档
$query = new MongoDB\Driver\Query([], ["limit" => 1, "sort" => ["_id" => -1]]);
$cursor = $manager->executeQuery("test.users", $query);
$document = $cursor->toArray()[0];
// 输出日期和时间戳
echo "Created at: " . $document->created_at->toDateTime()->format('Y-m-d H:i:s') . "\n";
echo "Timestamp: " . $document->timestamp . "\n";
在上面的代码中,我们首先连接到本地 MongoDB 数据库,然后创建一个 UTCDateTime
对象,该对象表示当前日期和时间。接下来,我们使用 BulkWrite
操作插入一个包含日期和时间戳的文档。我们将 UTCDateTime
对象存储在 created_at
字段中,并将其转换为 Unix 时间戳存储在 timestamp
字段中。
然后,我们使用 Query
操作查询刚刚插入的文档,并将结果转换为 PHP 数组。最后,我们输出 created_at
和 timestamp
字段的值。
注意,我们使用了 toDateTime()
方法将 UTCDateTime
对象转换为 PHP DateTime
对象,以便于格式化输出。
领取专属 10元无门槛券
手把手带您无忧上云