views:

30

answers:

2

I'm not sure what I'm doing wrong, but with MongoDB and PHP i'm trying to do this:

$db->textures->remove(array("_id"=>$_GET['texture_id']),array("safe" => true))

But nothing happens. I did a print_r and it says:

Array ( [err] => [n] => 0 [ok] => 1 )
A: 

Crap, looks like since im removing a MongoID i have to do this:

$db->textures->remove(array("_id"=>new MongoId($_GET['texture_id'])),array("safe" => true));
Oscar Godson
AFAIK only if the ID was added as a MongoID.
Hamish
Isn't _id always automatically added as a mongoid?
Oscar Godson
Yeah, if an _id is not supplied when it is created, then yes. A MongoId maps to an ObjectID which is an object, which is why just supplying the ID didn't work. But, you can supply your own (non-MongoID) _id values if you want, and search on them without using the MongoId object.
Hamish
eg, have a look at the following: > db.test.save({ name: "Test Object 1"}); > db.test.save({ _id: "abc123", "name" : "Test Object 2" }); > db.test.find(); { "_id" : ObjectId("4cca41c9d86d000000006d33"), "name" : "Test Object 1" } { "_id" : "abc123", "name" : "Test Object 2" }
Hamish
Gah, code formatting fail. See answer.
Hamish
oh! awesome. Thanks for that!
Oscar Godson
A: 

If an ID is not supplied when the record is saved then yes, you'll need to use the MongoID object to build the correct search criteria. You can, however, define the _id to be whatever you want - a plain integer, text, timestamp, etc - that you can use to search on as with any other property.

See the following CLI output as an example - the first object has an _id that contains an ObjectId type, but the second contains a simple string. A search by the string works as normal:

> db.test.save({ name: "Test Object 1"});
> db.test.save({ _id: "abc123", "name" : "Test Object 2" });
> db.test.find();
{ "_id" : ObjectId("4cca41c9d86d000000006d33"), "name" : "Test Object 1" }
{ "_id" : "abc123", "name" : "Test Object 2">
db.test.find({"_id" : "abc123"});
{ "_id" : "abc123", "name" : "Test Object 2" } }
Hamish
Just curious, but is there a way to have Mongo auto generate and ID as it does by default but make it a string? I like that the ids are long and near impossible to guess and that they are done by default. If not i can generate them myself, just curious if there was a way to just change the type on insert.
Oscar Godson
AFAIK, not that I know of, I'm no mongo guru though.
Hamish