Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

MongoDB: how to access or to create a collection within xollectoin or an aray within a collection

Hi All,

As you may know, mongodb does contain documents onto a collection.

A document is a key/value pair

the value can be an array, another document, an array of document or a single value.

Now i want to create and edit a document with the following structure :

(of courses services is

 $service       = new Services();
        $service->type = "server";
        $service->name = "OOO";
        $service->start = 01012013;
        //$service->specs = array();
        $service->specs = new stdClass();

Another way t do it is as well to create a $service->specs = array ( "cpu" => "386" , "ram" =>"64G")

the following object is created then :

{ "_id" : ObjectId("5291cb1d620d13bb390e9677"), "type" : "server", "name" : "OOO", "start" : 267275, "specs" : { "cpu" : "386", "RAM" : "64G" } }

my problem is the following:

if I need to manipulate the specs key/value, it is not an object but an array.

something like that :

$services = Services::find();

returns an array for the specs (and not an object)

so if I want to update the array, i need to update the whole array, if not i will lose the information.

I was expecting to have the specs to be an object with the mongodb "ODM",

so for exemple:


will update my object by keeping the cpu parts (but in reality it is not).

If i want to add another document within the documents, how do i do that.

if we need to manipulate the whole array each time we need to update a single information, ODM is not very useful in that case.

So what are the best practices?




Objects are always returned as associative arrays. It's something related to a difference between the way PHP and JavaScript implement objects.


array(2) {
    'cpu' => 
    string(3) "386"
    'RAM' => 
    string(4) "128G"

This works and updates a single array element without overwriting whole array:


Thanks for your reply,

yes that kind of things is working, ans i am able to update only the part i am interested in, but that really seems weird that we end up with an associated array and not an object.