Query only "sec" field from MongoDate using PHP

645 views Asked by At

I have a string converted to MongoDate using

$dateAdded = new MongoDate(strtotime("$time"));
echo "date ".$dateAdded;

So my $dateAdded now looks like 0.00000000 1482505458. (Here 1482505458 is the number of seconds and 0.00000000 is in microseconds.)

Now, I have a document in my collection which has sec = 1482442458 and usec = 622000.

 Array ( [_id] => Array ( [addedtime] => MongoDate Object ( [sec] => 1482505458 [usec] => 622000 ) )

How do I write a query which will only match the seconds field?

Update:

Hers's what I've been trying out :

$date = "2016-12-23 15:04:18";
$m = new MongoClient("mongodb://172.29.0.186:27017");
$dateAdded = new MongoDate(strtotime("+330 minutes",strtotime("$time")));
echo " date ".$dateAdded;

$key = array('$and' => array(array('_id.createdby' => "$user"), array('_id.addedtime' => "$dateAdded")));
$collectionCount->find($key);

And it should match :

 Array ( [_id.createdby] => 10006161 ) Array ( [_id] => Array ( [addedtime] => MongoDate Object ( [sec] => 1482505458 [usec] => 622000 ) [empname] => Praveen Valecha [createdby] => 10006161 ) )
1

There are 1 answers

1
Anubhav On

It's not a perfect solution but it's working for me and should work for most of the people who want to avoid searching for time as accurate as in microseconds.

Here's the part of code I modified from the one asked in the question:

I created a variable with time one minute greater than the time I'm searching for.

$dateAdded = new MongoDate(strtotime("+330 minutes",strtotime("$time")));
echo " dateAdded ".$dateAdded;
$dateFinal = new MongoDate(strtotime("+331 minutes",strtotime("$time")));
echo " dateFinal ".$dateFinal;

Then I used $gte and $lt to query for documents within a date range as suggested by @Sammaye.

$key = array('_id.addedtime' =>  array('$gte' => $dateAdded, '$lt' => $dateFinal));

NOTE : You can also add +1 second to $dateFinal in place of adding an extra minute to achieve more accurate results.