0

I want save many files using MongoDB's GridFS but I ran into some trouble by using my own id. My simplified code is the following:

<?php
$mongo = new Mongo();
$db = $mongo->myFiles;
$grid = $db->getGridFS();

var_dump($grid->storeBytes("ForTestingPurposes", array("_id" => new MongoID("mySampleId"), array("safe" => true))));
?>

I assumed that storeBytes() returns my own id (in this case "mySampleId") but what I get is something like this:

object(MongoId)#5 (1) { ["$id"]=> string(24) "50ae7542a34156852300003d" }

.. the automatically generated ID from Mongo. Is there anything wrong with my code above? Thanks for any suggestions...

Nrgyzer
  • 783
  • 1
  • 14
  • 38

1 Answers1

2

The PHP MongoId class is only for working with MongoDB ObjectIDs, which have a specific 12-byte format.

If you want to use a custom value for _id, just pass the string directly, eg:

$grid->storeBytes("ForTestingPurposes", array("_id" => 'mySampleId', array("safe" => true))));
Stennie
  • 63,885
  • 14
  • 149
  • 175
  • 1
    We should actually check for this value. There is a JIRA ticket for this: https://jira.mongodb.org/browse/PHP-554 – Derick Nov 22 '12 at 22:46
  • 1
    Alright, but by using a regular string, I run into some trouble by trying to persist the same ID multiple times... when I call my script the first time and an empty GridFS/MongoDB, everything works fine. By calling the script again and trying to persist the same id again, it also works fine... but why? I think _id must be unique... but my script does not throw anything by persist a file with the same id again... By calling the script again and again and again... I sometime get "Duplicate Error" but sometime not. By list the files of my GridFS after each call, the file was deleted sometimes. – Nrgyzer Nov 24 '12 at 09:40