John Davidson

Mongodb php datetime filter not working properly

0 comments
Message:


I use mongo db with php I need a last 1 hour data. I implement as like bellow.


{
"_id":{"$oid":"5ff42b30be00ec1eaf261db1"},
"logtype":"syslog",
"message":"Jan 4 06:51:56 4S-096 kernel: [70745743.387001] CPU7: Package temperature above threshold, cpu clock throttled (total events = 2955852254)",
"node_id":875,
"app_id":0,
"send_to_slack":1,
"created_date":{"$date":"2021-01-05T09:02:39.593Z"}
}

PHP CODE


$client = mongodb_connect();
$db = $client->$db_name;
$col = $db->selectCollection($collection_name);
$client->selectDatabase($db_name);

$criteria = array(
"created_date" => [$gte=> new \MongoDB\BSON\UTCDateTime(strtotime("-1 hour") * 1000)],
"logtype" => $logType,
"message" => trim($logdata),
"node_id" => $node_id,
);


$count = $col->count($criteria);

I need a count result. thanks in advance



My Answer:
$collection = (new MongoDB\Client)->mydb->mycollection;

$oneHourAgo = new DateTime('-1 hour');
$filter = ['timestamp' => ['$gte' => $oneHourAgo]];

$result = $collection->find($filter);

foreach ($result as $document) {
var_dump($document);
}

However, the above code may not work as expected because MongoDB stores dates in UTC timezone by default. So, you need to convert the current time to UTC before querying the database. Here's an updated version of the code:

php
$collection = (new MongoDB\Client)->mydb->mycollection;

$now = new DateTime();
$now->setTimezone(new DateTimeZone('UTC'));

$oneHourAgo = new DateTime('-1 hour');
$oneHourAgo->setTimezone(new DateTimeZone('UTC'));

$filter = ['timestamp' => ['$gte' => $oneHourAgo]];

$result = $collection->find($filter);

foreach ($result as $document) {
var_dump($document);
}


By setting the timezone to UTC for both the current time and the one hour ago time, you ensure that the query will return the correct results based on the UTC timezone used by MongoDB.

Rate this post

4 of 5 based on 2451 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us