0
votes

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?

2

2 Answers

0
votes

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:

  1. http://blog.mongodb.org/post/24960636131/mongodb-for-the-php-mind-part-1
  2. http://www.php.net/manual/en/book.mongo.php
  3. http://www.php.net/manual/en/mongo.tutorial.php
  4. http://www.php.net/manual/en/mongo.updates.php
0
votes

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));