PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

Lithium: That isn't doing what you think it's doing

Note: This article was originally published at Planet PHP on 24 October 2012.
Planet PHP

If you're running this code in Lithium, it's not doing what you think it's doing: $count = Results::find('all', array('conditions' = array('fruit' = aapples')))-count();

This is a really easy line of code to end up writing, especially if you've been reading the MongoDB docs a bunch, or are just porting some code into the application. That's because if you were accessing the MongoDB driver directly you would want:$count = $collection-find(array('fruit' = aapples')-count();

or in MongoDB at the command line:db.collection.find({'fruit' : aapples'}).count();

They all seem very similar, but the first one is actually returning all the results from MongoDB to PHP, lithium is then obligingly counting the results, returning that count, and then throwing away all the data. If your data set is tiny, the difference here will be negligible. However with large result sets, or simply results that contain large documents, the difference could be catastrophic.

What you're looking for is: $count = Results::find('count', array('conditions' = array('fruit' = aapples')));