Reputation: 4263
I want to insert my own unique value into the mongodb $id
field
I already have a unique key and I don't want to take up extra space with yet another index.
How can I do this with the PHP API?
Upvotes: 2
Views: 3193
Reputation: 395
$collection->save(array('_id' => new MongoId('my_mongo_id'), 'foo' => 'bar'));
Upvotes: 2
Reputation: 36300
I wrote a class to generate auto-increment values for Mongo in php You can check out my project on gitgub https://github.com/snytkine/LampCMS and look for /lib/Lampcms/MongoIncrementor class. It basically keeps track of per-collection "nextValue" value
Works great for me, maybe it will work for you too.
Also feel free to examine my classes, I use MongoDB and php heavily, maybe you can learn something from the code or maybe can show/teach me some cool mongo/php code.
Hope this helps.
Upvotes: -1
Reputation: 5830
The docs above explain this in a general way, but to give you a PHP-specific example you simply set the _id value to your generated id when you create the document:
<?php
$mongo = new Mongo();
$collection = $mongo->dbName->collectionName;
$id = your_id_generator(); // I assume you have one
$collection->save(array('_id' => $id, 'foo' => 'bar'));
print_r( $collection->findOne(array('_id' => $id)) );
Upvotes: 1
Reputation: 14873
check this link
http://www.mongodb.org/display/DOCS/Indexes#Indexes-UniqueIndexes
As long as you can guarantee uniqueness, you're not constrained to using the default "_id" MongoDB supplies.
Therefore, it's down to you how you generate this number. If you'd like to store this number inside MongoDB, then you could store it in a separate collection and increment it for every new URL required.
Incrementing a field is achieved by using the $inc verb, or you may want to take a look at how MongoDB can atomically update or increment a value. Unique IDs with mongodb
Upvotes: 0