No cache version.

Caching disabled. Default setting for this page:enabled (code LNG204)
If the display is too slow, you can disable the user mode to view the cached version.

Rechercher une fonction PHP

MongoDB::command

(PECL mongo >=0.9.2)

MongoDB::commandExecute a database command

Description

public MongoDB::command ( array $command [, array $options = array() [, string &$hash ]] ) : array

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.

This method is identical to:

<?php

public function command($data) {
    return 
$this->selectCollection('$cmd')->findOne($data);
}

?>

PHP: MongoDB::command - Manual Home of Manuel PHP  Contents Haut

Parameters

command

The query to send.

options

An array of options for the index creation. Currently available options include:

  • "socketTimeoutMS"

    This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a MongoCursorTimeoutException will be thrown and there will be no way to determine if the server actually handled the write or not. A value of -1 may be specified to block indefinitely. The default value for MongoClient is 30000 (30 seconds).

The following options are deprecated and should no longer be used:

  • "timeout"

    Deprecated alias for "socketTimeoutMS".

hash

Set to the connection hash of the server that executed the command. When the command result is suitable for creating a MongoCommandCursor, the hash is intended to be passed to MongoCommandCursor::createFromDocument().

The hash will also correspond to a connection returned from MongoClient::getConnections().

PHP: MongoDB::command - Manual Home of Manuel PHP  Contents Haut

Changelog

Version Description
1.5.0

Renamed the "timeout" option to "socketTimeoutMS". Emits E_DEPRECATED when "timeout" is used.

Added hash by-reference parameter.

1.2.0 Added options parameter with a single option: "timeout".

PHP: MongoDB::command - Manual Home of Manuel PHP  Contents Haut

Return Values

Returns database response. Every database response is always maximum one document, which means that the result of a database command can never exceed 16MB. The resulting document's structure depends on the command, but most results will have the ok field to indicate success or failure and results containing an array of each of the resulting documents.

PHP: MongoDB::command - Manual Home of Manuel PHP  Contents Haut

Examples

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

Finding all of the distinct values for a key.

<?php

$people 
$db->people;

$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() "distinct" example

Finding all of the distinct values for a key, where the value is larger than or equal to 18.

<?php

$people 
$db->people;

$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"
        
"query" => array("age" => array('$gte' => 18))
    )
);  

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

?>

The above example will output something similar to:


22
87

Example #3 MongoDB::command() MapReduce 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"),
    
"out" => array("merge" => "eventCounts")));

$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).

Note: Using MongoCode

This example uses MongoCode, which can also take a scope argument. However, at the moment, MongoDB does not support using scopes in MapReduce. If you would like to use client-side variables in the MapReduce functions, you can add them to the global scope by using the optional scope field with the database command. See the » MapReduce documentation for more information.

Note: The out argument

Before 1.8.0, the out argument was optional. If you did not use it, MapReduce results would be written to a temporary collection, which would be deleted when your connection was closed. In 1.8.0+, the out argument is required. See the » MapReduce documentation for more information.

Example #4 MongoDB::command() "geoNear" example

This example shows how to use the geoNear command.

<?php
$m 
= new MongoClient();
$d $m->demo;
$c $d->poiConcat;

$r $d->command(array(
    
'geoNear' => "poiConcat",      // Search in the poiConcat collection
    
'near' => array(-0.0851.48), // Search near 51.48°N, 0.08°E
    
'spherical' => true,           // Enable spherical search
    
'num' => 5,                    // Maximum 5 returned documents
));
print_r($r);
?>

PHP: MongoDB::command - Manual Home of Manuel PHP  Contents Haut

See Also

MongoDB core docs on » database commands.

Find a PHP function

English translation

You have asked to visit this site in English. For now, only the interface is translated, but not all the content yet.

If you want to help me in translations, your contribution is welcome. All you need to do is register on the site, and send me a message asking me to add you to the group of translators, which will give you the opportunity to translate the pages you want. A link at the bottom of each translated page indicates that you are the translator, and has a link to your profile.

Thank you in advance.

Document created the 30/01/2003, last modified the 26/10/2018
Source of the printed document:https://www.gaudry.be/en/php-rf-mongodb.command.html

The infobrol is a personal site whose content is my sole responsibility. The text is available under CreativeCommons license (BY-NC-SA). More info on the terms of use and the author.

References

  1. View the html document Language of the document:fr Manuel PHP : http://php.net

These references and links indicate documents consulted during the writing of this page, or which may provide additional information, but the authors of these sources can not be held responsible for the content of this page.
The author This site is solely responsible for the way in which the various concepts, and the freedoms that are taken with the reference works, are presented here. Remember that you must cross multiple source information to reduce the risk of errors.

Contents Haut