How to subtract two datetime in mongo php - php

Here I did the query for subtract but the result am getting null value. Is this correct way for subtract two datetime in project?
Code:
$arguments = array(
array(
'$project' => array(
'updatetime_difference' => array('$subtract' =>array('ISODate(2015-05-30T10:01:58.000Z)','$update_date')),
)
)
);
$result = $db->aggregate($arguments);

Related

Mongo $redact this object is already an operator expression Error

My goal is to subtract the current date from the stored date, and compared them to a saved interval value by the user.
I am running into the following error trying to use redact.
MongoResultException: localhost:27017: this object is already an operator expression, and can't be used as a document expression (at '0')
My code looks like this:
<?php
$ops = array(
array(
'$redact' => array(
'$cond' => array(
'if' => array(
'$gte' => array('$subtract' => array('$new Date()' , '$last_interacted_date'), '$reminder_interval')
),
'then' => '$$KEEP',
'else' => '$$PRUNE'
)
)
)
);
$results = $collection ->aggregate($ops);
For some reason the $subtract is causing this error. Why is the presence of subtract causing: "this object is already an operation expression'?
$new Date() is not valid here. You want MongoDate or MongoDB\BSON\UTCDateTime appropriate to your driver instead.
$ops = array(
array(
'$redact' => array(
'$cond' => array(
'if' => array(
'$gte' => array(
'$subtract' => array(
new UTCDateTime(round(microtime(true) * 1000)),
'$last_interacted_date'
),
'$reminder_interval'
)
),
'then' => '$$KEEP',
'else' => '$$PRUNE'
)
)
)
);
$results = $collection ->aggregate($ops);
The interpolation of the Date value actually happens in the "client" and "before" the aggregation pipeline is actually sent to the server. So you get the "milliseconds" as of "now" and send as a "BSON Date".
Note that this is "millseconds" in difference from the two BSON dates, so your "interval" needs to be in milliseconds, or otherwise do the math to convert further.

Retrieve data based on year and month in cakephp

I am trying to create a get statements function and I have some problems defining the date range.
The data will be passed via get method in the following format: ?year=yyyy&month=mm
The relevant column of the table has datetime type (2012-02-01).
I checked the TimeHelper class and more particularly the TimeHelper::daysAsSql($begin, $end, $fieldName, $timezone = NULL) but i am not sure if it applies for this case.
I was thinking if i can create a date in the format of Y-m using the two variables year and month and then use it in the conditions for retrieving the data but I am sure there is a more efficient and proper way. Could anyone help?
$user_id = $Client['Client']['id'];
$year = $this->request['url']['year'];
$month = $this->request['url']['month'];
//$date_created = date('Y-m');
if (!empty($user_id) && (!empty($date_created))) {
$Reports = $this->Report->find('all', array(
'fields' => array('amount','currency','date_created','invoice_no'),
'conditions' => array(
'Report.client_id'=> $user_id,
'Report.date_created >=' => $date_created,
'Report.date_created <=' => $date_created
),
)
);
MONTH(dateColumn) Returns an integer that represents the month of the specified date.
YEAR(dateColumn) Returns an integer that represents the year of the specified date.
InCakephp use as
$user_id = $Client['Client']['id'];
$year = $this->request['url']['year'];
$month = $this->request['url']['month'];
//$date_created = date('Y-m');
if (!empty($user_id) && (!empty($date_created))) {
$Reports = $this->Report->find('all', array(
'fields' => array('amount','currency','date_created','invoice_no'),
'conditions' => array(
'Report.client_id '=> $user_id,
'MONTH(date_created ) >='=> $month,
'YEAR(date_created ) <=' => $year
),
)
);

insert multiple rows in a saveall in cakephp

i'm newbie in Cake and wodering how to insert multiple rows in a single saveall function,
i got this table,
CREATE TABLE IF NOT EXISTS `dates` (
`date` varchar(10) COLLATE utf8_unicode_ci NOT NULL
)
what i'm trying to do is let user select start date and end date using JQuery calander, once submit all the dates between this range will be saved into database, i already got the array of dates eg:
`array(
(int) 0 => '5/8/2013',
(int) 1 => '6/8/2013',
(int) 2 => '7/8/2013',
(int) 3 => '8/8/2013',
)
`
then my controller looks like this:
public function index(){
if ($this->request->is('post')) {
$this->Date->create();
$data = array();
$data['dates']=array();
$startDate = $this->request->data['Date']['from'];
$endDate = $this->request->data['Date']['to'];
$datesBlocked = $this->loopDates($this->request->data['Date']['from'],$this->request->data['Date']['to']);
$data['dates'][] = $this->request->data['Blockdate']['from'];
$data['dates'][] = $this->request->data['Blockdate']['to'];
/*foreach($datesBlocked as $data) {
$data['dates'][] = $data;
}*/
if($this->Date->saveAll($data)) {
$this->Session->setFlash(__('done'));
if ($this->Session->read('UserAuth.User.user_group_id') == 1) {
// $this->redirect("/manages");
}
}
}
public function loopDates($from,$to){
$blockdates = array();
$start = strtotime($from);
$end = strtotime($to);
debug($start);
$counter = 0;
for($t=$start;$t<=$end;$t+=86400) {
$d = getdate($t);
$blockdates[$counter++] = $d['mday'].'/'.$d['mon'].'/'.$d['year'];
}
debug($blockdates);
return $blockdates;
}
issue was i can't get foreach work, if i uncomment the foreach, i got error said Illegal string offset 'dates' , so i commented that and try to only add the start date and end date to the array to see if that works, then i got another error said.
`array(
'dates' => array(
(int) 0 => '08/05/2013',
(int) 1 => '09/05/2013'
)
)
`
Notice (8): Array to string conversion [CORE\Cake\Model\Datasource\DboSource.php, line 1005]Code
cuz i'm trying to insert 2 values into one field...i know it should be sth like
`array(
'dates' => array( (int) 0 => '08/05/2013',
)
'dates' => array((int) 1 => '09/05/2013'
))
`but can't figure out how to do it. Any help would be much appreciate!!!!
The structure you'll want your array to save multiple dates using saveAll() is this:
array(
'Date' => array(
0 => array(
'date' => '08/05/2013',
),
1 => array(
'date' => '09/05/2013',
)
),
)
I know that this is a little late, but to write multiple rows in a loop, you have to proceed the save with a create().
eg:
foreach($items as $lineItem){
$this->Invoice->create();
$this->Invoice->save(array(
'user_id'=>$property['User']['id'],
'invoice_id'=>$invId['Invoices']['id'],
'item_id'=>$lineItem['item_number'],
'quantity'=>$lineItem['quantity'],
'price'=>$lineItem['mc_gross']
);
}
Just thought it was worth mentioning, hopefully it will help someone.

How to search in fulltext index using php in mongodb

I'm using mongodb 2.4 and added fulltext index to the "title" field in one the collection. How should I search something in that field using php?
This is the code I use right now:
$params = array(
'_id' => array(
'$gt' => (int)$gt
)
);
$r = $this->collection->find( $params )->limit($limit);
This seem to be the answer to my question:
<?php
$result = $db->command(
array(
'text' => 'bar', //this is the name of the collection where we are searching
'search' => 'hotel', //the string to search
'limit' => 5, //the number of results, by default is 1000
'project' => Array( //the fields to retrieve from db
'title' => 1
)
)
);
http://www.php.net/manual/en/mongodb.command.php#111891

Lithium & MongoDB: Finding documents by date range

I have numerous documents containing a field called "date" which is simply a unix timestamp.
whithin lithium, i want to find all documents in a given date range. i'm currently trying the following:
//$_stats contains two \DateTime objects which are properly initialized
$transactions = Transactions::all(
array('conditions' => array(
'tags' => array('$all' => array((string)$tag->_id)),
'date' => array('$gte' => array((int)$_stats['date_start']->getTimestamp()), '$lte' => array((int)$_stats['date_end']->getTimestamp()))
))
);
But this returns zero documents. When I remove the "date" condition, it works fine and I get all documents.
What am I missing?
Thanks, aenogym
There doesn't seem to be any need of giving an array of dates, so perhaps try:
$transactions = Transactions::all(
array('conditions' => array(
'tags' => array('$all' => array((string)$tag->_id)),
'date' => array('$gte' => (int)$_stats['date_start']->getTimestamp(), '$lte' => (int)$_stats['date_end']->getTimestamp())
))
);
Keep in mind that MongoDate stores dates as miliseconds while timestamp uses seconds. In other words MongoDate has higher precision.

Categories