Chuong Phan
Chuong Phan

Reputation: 3

edit array in mongodb - PHP

My data like this:

Array
(
    [_id] => MongoId Object
        (
            [$id] => 51a6fca3f348aca011000000
        )

    [first_name] => Phan
    [last_name] => Chuong
    [interests] => Array
        (
            [0] => football
            [1] => swimming
            [2] => PHP
            [3] => music
        )

)

I want edit value PHP to PHP1 or set PHP to null. Please help me how can i do it? Thanks all!

Upvotes: 0

Views: 76

Answers (1)

joschua011
joschua011

Reputation: 4207

You could use the MongoCollection::update() method like this:

// $c is your MongoCollection Object

$updatedata = array('$set' => array("interests.2" => "PHP1"));
$id = new MongoID('51a6fca3f348aca011000000')
$c->update(array("_id" => $id), $updatedata);

The update method needs two arrays, the first one will tell the DB which Object to update ( In this example where id = our id, always use the MongoID Object, always!), the second array defines what to update, note that you can get to values in nested arrays wit the dot like above. $set is an Field Update Operator, read more on them here: http://docs.mongodb.org/manual/reference/operator/update-field/

Or you could just get the entire Array, change it, and save it back.

$cursor = $c findOne("_id",4cb30f560107ae9813000000);
$cursor['interests'][2] = 'whatever';
$c->update($cursor);

Upvotes: 2

Related Questions