How to insert array values(php) in MongoDB?-ThrowExceptions

Exception or error:

My contents of MongoDB(when i used find()) is like this:

{ "_id" : ObjectId("50072b17b4a6de3b11000001"), "addresses" : [
    {
            "_id" : ObjectId("50072b17b4a6de3b11000004"),
            "address1" : "770 27th Ave",
            "address2" : null,
            "city" : "San Mateo",
            "country" : "United States",
            "country_code" : "US",
            "name" : "home",
            "primary" : true,
            "state" : "California",
            "zip" : "94403"
    }
], "biography" : null, "category_ids" : [ ], "department" : null, "emails" : [
    {
            "_id" : ObjectId("50072b17b4a6de3b11000003"),
            "_type" : "Email",
            "name" : "work",
            "email" : "alan@altimetergroup.com"
    }
 ] }

What I need to do is I need to update this MongoDB with additional datas’s. For that I need to get the values in php as an array and insert that array in to this collection. How to get the values for these specified fields as an array in php and how to insert those in php??

How to solve:
$array = $this->collection->findOne(array('_id' => MONGO_ID));
//Update things
$this->collection->update(array('_id' => $array['_id']), $array);

MONGO_ID in my example should represent the ‘_id’ MongoDB automatically assigns. Make sure it is sent as an Object, and not as a string.

Answer:

If you want to add another entry, you add an entry like so:

$this->collection->insert($array_of_data, array('safe' => true));

Answer:

For insert:

$id = new MongoId();
$test->insert(array('t' => 'test', 'email' => array('_id' => $id, 'email' => 'ccc@ccc.com')));

And the result:

{ "_id" : ObjectId("5088cba86527044a31000001"), "t" : "test", "email" : { "_id" : ObjectId("5088cba86527044a31000000"), "email" : "ccc@ccc.com" } }

It works 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *