I'm using MongoDB with PHP and I want to update all fields in a document if it matches certain criteria.
Each document has a title - if the title matches I want to update all the fields within that document with the values of the new document.
Here's some pseudocode:
if doc.title == newdoc.title
replace doc with newdoc
else
insert newdoc
How would I go about this in MongoDB?
An example of how to do an update to replace an entire document, is here:
update(array("username" => "joe"), array('$set' => array("twitter" => "@joe4153")));
How familiar are you with the MongoDB PHP driver? If you are new to it, I would recommend the following resources/tutorial:
I did not have the 'upsert' flag set to true - otherwise a new document is inserted with a new _id...
http://docs.mongodb.org/manual/tutorial/insert-documents/
The code below overwrites the entire file if the document's name value is 'johnsmith'...
$collection->update(array('name' => 'johnsmith'),
array('name' => 'bobsmith, 'occupation' => 'plumber'),
array('upsert'=>true));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.