0

I am working in doctrine ODM. I am new to doctrine.. Actually i am trying to delete all the data from a collection which are all inserted today using querybuilder. But i am not able to do that. Please help me on this. The querybuilder what i am trying to use is below,

.....->createQueryBuilder('Document')
           ->remove()
           ->field('active')->equals(1)
           ->where('createdOn')->equals(new MongoDate(date()))
           ->getQuery();
Vinoth Babu
  • 6,724
  • 10
  • 36
  • 55

1 Answers1

0

Well the following:

new MongoDate(date())

Is really a little bit too granular as it is unlikely you have anything with that exact timestamp value and it certainly is not the whole day.

What you want to find is the "range" between today and the next day So first work out the dates:

  $date = new DateTime();                       # Time right now
  $ts = $date->getTimestamp();

  $today = $ts - ( $ts % ( 60 * 60 * 24 ) );    # Round to the day
  $tomorrow = $today + ( 60 * 60 * 24 );        # Add one day to that

  $start = new MongoDate( $today );
  $end = new MongoDate( $tomorrow );

Then call the values on the "range":

(...)->createQueryBuilder('Document')
       ->remove()
       ->field('active')->equals(1)
       ->where('createdOn')->range( $start, $end )
       ->getQuery()
       ->execute();

Normally expressed with $gt and $lt operators in MongoDB query terms, but the doctrine DSL has a combined operator to represent a range.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • @VinothBabu is "createdOn" an actual BSON date object in MongoDB? If so it will show as `ISODate()` in the shell or otherwise correctly inflate as a `MongoDate()` from PHP code. – Neil Lunn Jan 06 '15 at 06:49
  • @VinothBabu maybe I was being a bit literal in the "cut and paste" from your code. Were you ever calling `.execute()`? Aside from that there must be some data problem here, wrong collection, other conditions in your query that does not match. Check for these and check your data. – Neil Lunn Jan 06 '15 at 07:49
  • i have made that to work by using lte and gte as ->field('createdOn')->gte($from) and ->field('createdOn')->lte($to) – Vinoth Babu Jan 06 '15 at 08:27
  • @VinothBabu Interesting. Not sure why `->range()` would be failing here where it should just be shorthand for the same thing. – Neil Lunn Jan 06 '15 at 09:03