PHP Velho Oeste 2024

La clase MongoId

(PECL mongo >=0.8.0)

Advertencia

Esta extensión que define esta clase está obsoleta. En su lugar debe usarse la extensión MongoDB. Las alternativas a esta clase son:

Introducción

Identificador único creado para objetos de bases de datos. Se se inserta un objeto sin un campo _id en una base de datos , éste se añadirá con una instancia de MongoId. Si los datos tuvieran un campo único natural (p.ej., un nombre de usuario o una marca de tiempo) no habría problema en usarlo como _id, y en este caso no se reemplazaría por un MongoId.

Las instancias de MongoId cumplen la función de los campos autoincrementales de las base de datos relacionales: ofrecen una clave única cuando los datos no tienen una clave natural. Los autoincrementales no funcionan correctamente en bases de datos compartidas, ya que es difícil determinar el siguiente número de la secuencia. Esta clase establece las limitaciones necesarias para generar rápidamente un valor único entre servidores compartidos.

Cada MongoId contiene 12 bytes (componiendo un string de 24 caracteres hexadecimales). Los cuatro primeros bytes son un timestamp, los tres siguientes son un hash del nombre de máquina del cliente, los dos siguiente son los bytes menos significativos del id del proceso en ejecución del script, y los últimos tres corresponden a un valor incremental.

MongoId es serializable y deserializable. Su forma serializada es similar a su forma en string:

C:7:"MongoId":24:{4af9f23d8ead0e1d32000000}

Sinopsis de la Clase

MongoId {
public string $$id = NULL ;
/* Métodos */
public __construct ([ string|MongoId $id = NULL ] )
public static getHostname ( void ) : string
public getInc ( void ) : int
public getPID ( void ) : int
public getTimestamp ( void ) : int
public static isValid ( mixed $value ) : bool
public static __set_state ( array $props ) : MongoId
public __toString ( void ) : string
}

Campos

$id
Este campo contiene la respresentación string de este objeto.

Nota: El nombre de la propiedad comienza con un carácter $. Se podría acceder a ella empleando la sintaxis analizada de variables complejas (p.ej., $mongoId->{'$id'}).

Ver también

Documentación de MongoDB sobre » ObjectIds.

Tabla de contenidos

add a note add a note

User Contributed Notes 7 notes

up
8
Lionel
10 years ago
Just to be careful with the strict comparison. Object inequalities holds.

<?php

$m1
= new MongoId('51b14c2de8e185801f000006');
$m2 = new MongoId('51b14c2de8e185801f000006');

var_dump($m1 === $m2); //gives you boolean false
var_dump($m1 == $m2); //gives you boolean true

$m3 = new MongoId('51b14c2de8e185801f000006');
$m4 = new MongoId('51b14c2de8e185801f000007');

var_dump($m3 === $m4); //gives you boolean false
var_dump($m3 == $m4); //gives you boolean false

?>
up
7
rmarscher
11 years ago
You can also cast the id to a string rather than access the $id property to get a string representation of the MongoId.

<?php
$stringId
= (string) $mongoId;
?>
up
5
georgedot dont spam me gmail caom
10 years ago
Due to Recent changes.

* [PHP-554] - MongoId should not get constructed when passing in an invalid ID.

Constructor will throw an exception when passing invalid ID.

<?php

$_id
= new MongoId(); //Generates new ID
$_id = new MongoId(null); //Generates new ID

$_id = new MongoId("invalid id"); //throws MongoException

?>

<?php
//Revert to old behaviour
$_id = "invalid id";
try {
   
$_id = new MongoId($_id);
} catch (
MongoException $ex) {
   
$_id = new MongoId();
}
?>

<?php
//Nifty hack
class SafeMongoId extends MongoId {

    public function
__construct($id=null) {

        try {
           
parent::__construct($id);
        } catch (
MongoException $ex) {
           
parent::__construct(null);
        }

    }
}
?>
up
2
Ryan S
11 years ago
it is important to note that

<?php
   
array("_id" => new MongoId("50cf7d2841d41f4f35000000"))
//                   ≠
   
array("_id" => array("$id" => "50cf7d2841d41f4f35000000"))
?>

This issue can arrise when using json_encode() and json_decode(). If not paying close enough attention one can assume due to the encoded value of the object that it is just this simple:

<?php
    $item
= $db->myCollection->findOne();
    print
json_encode($item);
   
// {"_id": {"$id": "50cf7d2841d41f4f35000000"}}
   
$item = $db->myCollection->findOne(json_encode($item));
   
// $item is empty aka not found
?>

Simple solution to handle these situations:

<?php
   
class MongoId2 extends MongoId {
        public function
__construct($id = null) {
            if(
is_array($id)) {
               
$id = (object) $id;
            }

            if(
is_object($id) && isset($id->{'$id'})) {
               
$id = $id->{'$id'};
            }

            return
parent::__construct($id);
        }
    }
?>
up
2
lensvil dot co at gmail dot com
7 years ago
Get ObjectId MongoDB via PHP

var_dump($object);

object(MongoDB\Model\BSONDocument)#36 (1) {
  ["storage":"ArrayObject":private]=>
  array(8) {
    ["_id"]=>
    object(MongoDB\BSON\ObjectID)#33 (1) {
      ["oid"]=>
      string(24) "573e69e78fccd968aa066611"
    }
    ["dummy"]=>
    string(5) "mongo"
  }
}

Failure
var_dump($object->_id->oid);
>>> null

var_dump($object->_id->{'oid'});
>>> null

var_dump($object->_id->{'$oid'});
>>> null

Success
$bson = \MongoDB\BSON\fromPHP($object);
$json = \MongoDB\BSON\toJSON($bson);
$result = json_decode($json, true);

var_dump($result['_id']['$oid']);
>>> string(24) "573e69e78fccd968aa066611"
exit;
up
2
sararschreiber at gmail dot com
13 years ago
this is useful for querying for an object by id, given the id's hex:

<?php
$userid
= '4cb4ab6d7addf98506010000';

$theObjId = new MongoId($userid);

$connection = new Mongo();
$db = $connection->thedb->users;

// this will return our matching entry.
$item = $db->findOne(array("_id" => $theObjId));

$connection->close();

?>
up
2
alex dot turpin at gmail dot com
12 years ago
If you need to get the actual ID string, and you try the usual way, PHP will whine because it starts with a dollar sign and it thinks it's a variable. Instead, use this notation:

<?php
    $mongoid
->{'$id'} //Get the $id property of a MongoId object
?>
To Top