The MongoDB\BSON\ObjectId class

(mongodb >=1.0.0)

Introduction

Type BSON pour un » ObjectId. La valeur se compose de 12 octets, où les quatre premiers octets sont un timestamp qui reflètent la création de l'ObjectId. Plus précisément, la valeur se compose de :

  • une valeur de 4 octets représentant les secondes depuis l'époque UNIX,
  • un nombre aléatoire de 5 octets unique à une machine et un processus, et
  • un compteur de 3 octets, commençant par une valeur aléatoire.

Dans MongoDB, chaque document stocké dans une collection requiert un champ _id unique qui agit comme clé primaire. Si un document inséré omet le champ _id, le pilote génère automatiquement un ObjectId pour le champ _id.

L'utilisation d'ObjectId pour le champ _id fournit les avantages supplémentaires suivants:

  • L'heure de création de l'ObjectId peut être accédée à l'aide de la méthode MongoDB\BSON\ObjectId::getTimestamp().
  • Le tri sur un champ _id qui stocke des valeurs ObjectId équivaut à peu près au tri par date de création.

Synopsis de la classe

/* Méthodes */
final public __construct(?string $id = null)
final public getTimestamp(): int
final public jsonSerialize(): mixed
final public serialize(): string
final public __toString(): string
final public unserialize(string $data): void
}

Historique

Version Description
PECL mongodb 1.12.0 Implémente Stringable pour PHP 8.0+.
PECL mongodb 1.3.0

Renommé de MongoDB\BSON\ObjectID vers MongoDB\BSON\ObjectId.

Implémente MongoDB\BSON\ObjectIdInterface.

PECL mongodb 1.2.0 Implémente Serializable et JsonSerializable.

Sommaire

add a note

User Contributed Notes 2 notes

up
28
naip1984 at gmail dot com
6 years ago
I struggled for awhile to identify the way to find() using a ObjectID

This seems to work, I hope this helps someone else out.

$mongoId = '5a2493c33c95a1281836eb6a';

$collection->find(['_id'=> new MongoDB\BSON\ObjectId("$mongoId")]);

I found it here: https://docs.mongodb.com/php-library/current/reference/method/MongoDBCollection-findOne/

Note this is for the PHP library, not the legacy library.
up
9
Mike T
5 years ago
Worth noting this will throw an InvalidArgumentException if string is not in the correct format
To Top