简体   繁体   中英

MongoDB Update All Fields If Document Exists PHP

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:

  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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM