I don't know how CodeIgniter's MongoDB API is different than the one from the driver, but you have to instantiate a new instance of MongoId
and pass it to the query, like this:
$m = new MongoClient(...);
$col = $m->selectCollection(...);
$cursor = $col->findOne(array('_id' => new \MongoId($id)));
This is due to how MongoDB saves its _id column. http://docs.mongodb.org/manual/core/object-id/
If you were to supply a simple string as the _id column when creating a new document, you wouldn't have to instantiate a new object of MongoId
every time you query for it. Keep in mind that you have to care about unique identities and cardinalities on your own if you do that, since MongoDB does not provide the option of AUTO_INCREMENT
for certain colums like relational tables (MySql, PgSql, ...) do. Instead it gives each document a uniquely generated id object to act as the primary key.
The reason for the _id
column to use generated objects not related to the collection itself as default is, uhm, because internally it is a bunch of stitched bytes, and comparing raw bytes for sorting for example is way faster than interpreting it as string characters while comparing, having to mess around with alphabetical orders and the like, while raw bytes can be compared logically, which is way faster. And believe me, you WILL want it to be faster when you query 100,000,000+ documents, which is usual for decent sized MongoDB instances. Using a technique like AUTO_INCREMENT
ed primary keys also won't allow for sharded databases easily, since you want to make sure that each index follows each other when inserting a new document, which will sure block other insertions within the same collection. This is why generated objects instead of AUTO_INCREMENT
keys are used.