Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

Mongodb php datetime filter not working properly

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  MongoDBBSONUTCDateTime(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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I am not so familiar with PHP, but I think $client->$db_name is equal to $client->selectDatabase($db_name)

However -> does not work with variables, so $client->$db_name may fail.

Try this one:

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

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

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

I never used strtotime, maybe you have to skip * 1000


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...