Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MongoDB, update document without erasing the rest

Tags:

mongodb

I'm trying to update a mongo document, using PHP and the update() function. However, when I do this, it replaces the WHOLE document with the value I wanted to update. How can I fix this?

The code I have written up to now: http://twaddlr.com/view/73 (Scroll down to the "update" function. It's a database wrapper I'm writting for my site)

like image 678
user697108 Avatar asked Apr 11 '11 14:04

user697108


1 Answers

The key is to use $set in the update, e.g. instead of this (sorry using JavaScript syntax here, not sure about the exact PHP driver syntax):

db.my_collection.update({hello: "world"}, {foo: "bar"})

you do

db.my_collection.update({hello: "world"}, {$set: {foo: "bar"}})

If you use $set, only the properties you specify will be updated, the whole document will not be replaced.

You can read more about this in the documentation, here: http://www.mongodb.org/display/DOCS/Updating#Updating-ModifierOperations

Edit: looking at your code, this is exactly what you do in the addRow method. Just do the same thing in update.

like image 133
Theo Avatar answered Oct 24 '22 17:10

Theo