downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

MongoDB::__construct> <MongoDB::authenticate
Last updated: Fri, 20 Nov 2009

view this page in

MongoDB::command

(PECL mongo >=0.9.2)

MongoDB::commandExecute a database command

Description

public array MongoDB::command ( array $data )

Almost everything that is not a CRUD operation can be done with a database command. Need to know the database version? There's a command for that. Need to do aggregation? There's a command for that. Need to turn up logging? You get the idea.

Parameters

data

The query to send.

Return Values

Returns database response.

Examples

Example #1 MongoDB::command() "distinct" example

Finding all of the distinct values for a key.

<?php

$people
->insert(array("name" => "Joe""age" => 4));
$people->insert(array("name" => "Sally""age" => 22));
$people->insert(array("name" => "Dave""age" => 22));
$people->insert(array("name" => "Molly""age" => 87));

$ages $db->command(array("distinct" => "people""key" => "age"));

foreach (
$ages['values'] as $age) {
    echo 
"$age\n";
}

?>

The above example will output something similar to:


4
22
87

Example #2 MongoDB::command() map/reduce example

Get all users with at least on "sale" event, and how many times each of these users has had a sale.

<?php

// sample event document
$events->insert(array("user_id" => $id
    
"type" => $type
    
"time" => new MongoDate(), 
    
"desc" => $description));

// construct map and reduce functions
$map = new MongoCode("function() { emit(this.user_id,1); }");
$reduce = new MongoCode("function(k, vals) { ".
    
"var sum = 0;".
    
"for (var i in vals) {".
        
"sum += vals[i];"
    
"}".
    
"return sum; }");

$sales $db->command(array(
    
"mapreduce" => "events"
    
"map" => $map,
    
"reduce" => $reduce,
    
"query" => array("type" "sale")));

$users $db->selectCollection($sales['result'])->find();

foreach (
$users as $user) {
    echo 
"{$user['_id']} had {$user['value']} sale(s).\n";
}

?>

The above example will output something similar to:


User 47cc67093475061e3d9536d2 had 3 sale(s).
User 49902cde5162504500b45c2c had 14 sale(s).
User 4af467e4fd543cce7b0ea8e2 had 1 sale(s).


add a note add a note User Contributed Notes
MongoDB::command
There are no user contributed notes for this page.

MongoDB::__construct> <MongoDB::authenticate
Last updated: Fri, 20 Nov 2009
 
 
show source | credits | sitemap | contact | advertising | mirror sites