0
votes

Im pretty new to MongoDB and have some minor troubles with it. In Mongo, every object I get from my database has that special _id field. This field is of course needed to uniquely identify my object.

Now in PHP, my object is returned as an array with the special _id field.

Array (
    [_id] => MongoId Object (
        [$id] => 547dc96b5c5db8a80f000029
    )
    [somekey] => somevalue
)

When encoding to JSON, sending through some frontends and decoding it back in PHP again, the _id field has of course been cast/destroyed.

To avoid this, I think I'll have to cast the _id field after getting it from the Mongo database.

Array (
    [_id] =>  547dc96b5c5db8a80f000029
    [somekey] => somevalue
)

Now it can safely be encoded and decoded however I want.

But will this object work when saved in the MongoDB again? Will Mongo use the _id field as it's Mongo ObjectId even in this form or do I need to recast it accordingly?

Is there a better way for this?


Update I just tried saving an object several times with it's _id as MongoId and with it's _id as a string. Objects with MongoId are not replacing those with same _id as string, type matters here.

This would meand that every object I get from the db needs it's _id to be manually cast and after it's received from some JSON using client again, I would have to recast evrry _id to MongoId again. This might have a severe performance impact when loading larger lists of objects.

Is there a better way?

1
Change string represented _id back to an object? $array['_id'] = new MongoId('547dc96b5c5db8a80f000029');Glavić
@Glavić So you think I will have to recast every _id back to MongoId objects before sending them to the database again?ToBe
Easiest way would be to test this, but I think that if _id is presented as string, it will replace object in mongodb. Please try it...Glavić
@Glavić Tried it. see update. Strange...ToBe
So _id is treated as unique field, no matter what type it has. is how mongodb works. Field _id is always unique field, no matter what type it is; and this is the how it should work.Glavić

1 Answers

1
votes

You should change string represented field _id back to an MongoId object:

$array['_id'] = new MongoId($array['_id']);

I don't think this will be severe performance impact, best to test it. On other hand, you can still create your own type for _id field, integer or string, it doesn't have to be an object.