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?
_id
back to an object?$array['_id'] = new MongoId('547dc96b5c5db8a80f000029');
– Glavić_id
is presented as string, it will replace object in mongodb. Please try it... – Glavić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ć