PHP queries with MongoDB

May 8th, 2010 | Tags: ,

How to return selected fields from query.

// Query against the following field(s)

$query = array( “username” => $profile_id);

// Return only the following field(s)

$fields = array(”username”, “age”, “tags”, “gender”, “seeking”, “email”);

// Execute the query

$data = $collection->findOne( $query,$fields );

How to sort query by specific field.

// Here we sort by username in descending order.

$collection->find(array(”tags” => $tag))->sort(array(”username” => -1));

Pagination with MongoDB

// Let’s set the necessary variables.

$docs_per_page = 10;

$total_documents = $collection->find(array(”recipient” => $user))->count();
$skip = (int)($docs_per_page * ($page – 1));
$limit = $docs_per_page;
$total_pages = ceil($total_documents / $limit);

// Now execute

$collection->find(array(”recipient” =>$user))->limit($limit)->skip($skip)->sort(array(”_id” => -1));

1 trackbacks

  1. ehcache.net Trackback | 2011/03/20