Devin Dixon
Devin Dixon

Reputation: 12443

Subtracting Dates in Mongo

I am trying to substract two dates in MonoDB using the aggreation framework.

My code looks like this:

$ops = array(
    array('$project' => array("fieldMath" => 
    array( '$subtract' => array( 'new ISODate()', 'new ISODate("last_interacted_date")' )),

     )),
    array('$match' => array('fieldMath' => array('$gte' => 2),
    ),
     ),
);
$object -> aggregate($ops);

The problem is I'm getting an error that I am trying to substract 2 string.

Fatal error: Uncaught exception 'MongoResultException' with message 'localhost:27017: cant $subtract aString from a String

new ISODate and the last_interacted_date are both ISODate objects.

My goal is to subtract a 'last_did_something' date from the date today, and return results for all queries that are within 2 days.

What am I doing wrong and how I can subtract dates?

Upvotes: 0

Views: 984

Answers (1)

chridam
chridam

Reputation: 103475

Since you want to query for documents that have the last_interacted_date date field greater than or equal to the date two days ago, you need to create a new date object (2 days ago date) that you can use as your query comparison. The following demonstrates this:

$start = new MongoDate(strtotime( "-2 days"));
$ops = array(
    array("$match" => array(
       "last_interacted_date" => array("$gte" => $start)
       )
    )    
);
$object -> aggregate($ops);

You can use a nifty library called Carbon that can help dealing with date/time in PHP much easier and more semantic so that your code can become more readable and maintainable:

// get the current time
$current = Carbon::now();

// subtract 2 days to the current time
$start = $current->subDays(2);

$ops = array(
    array("$match" => array(
        "last_interacted_date" => array("$gte" => $start)
        )
    )    
);
$object -> aggregate($ops);

Upvotes: 1

Related Questions