2

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?

Justin
  • 4,203
  • 7
  • 41
  • 58

4 Answers4

2
$collection->save(array('_id' => new MongoId('my_mongo_id'), 'foo' => 'bar'));
jhavrda
  • 403
  • 2
  • 13
  • 1
    This does work, but you don't even have to use the MongoID class. You can just use your own hash as the *_id* value – dtbarne Jun 28 '12 at 01:56
1

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)) );
therealjeffg
  • 5,790
  • 1
  • 23
  • 24
0

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

Community
  • 1
  • 1
Pramendra Gupta
  • 14,667
  • 4
  • 33
  • 34
-1

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.

Dmitri
  • 34,780
  • 9
  • 39
  • 55