2

I'm trying to update a MongoDB document via PHP. My problem is that the documents data are removed when i update, thus other data than what I update is gone.

Before I update, the document looks like this:

{
    "_id": {
        "$oid": "4e178b45419866350f000001"
    },
    "Twitter": {
        "_id": {
            "$oid": "4e178b45419866350f000000"
        },
        "created": {
            "$date": "2011-07-08T22:57:09Z"
        },
        "userid": "5552362"
    },
    "created": {
        "$date": "2011-07-08T22:57:09Z"
    }
}

Here's how I update:

    $r = $Profile->update(
        array('Twitter._id' => new MongoId($profile['_id'])),
        array(
            '$set' => array(
                'Twitter' => array(
                    'name' => $user['name'],
                    'username' => $user['screen_name'],
                    'url' => $user['url'],
                    'modified' => new MongoDate()
                )
            )
        ),
        array('safe' => true)
    );
    debug($r); 
webjay
  • 5,358
  • 9
  • 45
  • 62
  • possible duplicate of [Updating nested documents in mongodb](http://stackoverflow.com/questions/1145956/updating-nested-documents-in-mongodb) –  Jul 09 '11 at 09:44
  • And how does the document look after you have done the update? – Theo Jul 09 '11 at 10:26
  • You shouldn't prefix your properties with `$`, see http://www.mongodb.org/display/DOCS/Legal+Key+Names – Theo Jul 09 '11 at 10:32
  • `$set` is not a key, but a [modifier](http://www.mongodb.org/display/DOCS/Updating#Updating-%24set). – webjay Jul 09 '11 at 22:05

1 Answers1

5

I think you want this kind of update:

$Profile->update(
    array('Twitter.userid' => $user['id']),
    array(
        '$set' => array(
            'Twitter.name' => $user['name'],
            'Twitter.username' => $user['screen_name'],
            'Twitter.url' => $user['url'],
            'Twitter.modified' => new MongoDate()
        )
    ),
    array('multiple' => true)
);
webjay
  • 5,358
  • 9
  • 45
  • 62
pingw33n
  • 12,292
  • 2
  • 37
  • 38