The MongoId class
(PECL mongo >=0.8.0)
Introduction
A unique identifier created for database objects. If an object is inserted into the database without an _id field, an _id field will be added to it with a MongoId instance as its value. If the data has a naturally occuring unique field (say, a username or timestamp) it is fine to use this as the _id field instead, and it will not be replaced with a MongoId.
Instances of the MongoId class fulfill the role that autoincrementing does in a relational database: to provide a unique key if the data does not natually have one. Autoincrementing does not work well with a sharded database, as it is impossible to find what the next number should be quickly. This class fulfills the constraints of quickly generating a value that is unique across shards.
Each MongoId is 12 bytes (making its string form 24 hexidecimal characters). The first four bytes are a timestamp, the next three are a hash of the client machine's hostname, the next two are the two least significant bytes of the process id running the script, and the last three bytes are an incrementing value.
MongoIds are serializable/unserializable. Their serialized form is similar to their string form:
C:7:"MongoId":24:{4af9f23d8ead0e1d32000000}
Class synopsis
Fields
- id
- This field contains the string representation of this object.
See Also
MongoDB core docs on » ids.
Table of Contents
- MongoId::__construct — Creates a new id
- MongoId::getHostname — Gets the hostname being used for this machine's ids
- MongoId::getInc — Gets the incremented value to create this id
- MongoId::getPID — Gets the process ID
- MongoId::getTimestamp — Gets the number of seconds since the epoch that this id was created
- MongoId::isValid — Check if a value is a valid ObjectId
- MongoId::__set_state — Create a dummy MongoId
- MongoId::__toString — Returns a hexidecimal representation of this id
Коментарии
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();
?>
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
?>
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;
?>
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);
}
}
?>
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);
}
}
}
?>
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
?>
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;