Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How to 'upsert' (update or insert) MongoDB in ODM?

Hello, could anyone told me how to perform an upsert operation in ODM (Object-Document Mapper) ? In MongoDB native driver, there is a parameter upsert in update operation which could perform an upsert operation, but I can't found this in Phalcon ODM.

The upsert operation is that update the record if exists and insert if record does not exist.


Use the save() method of the Collection class, similar to the The ODM uses the save() method of the driver, but also gives tons of extras with it.

Thanks for your reply ! But I found that it is not powerful enough..

Eg: I have an 'emailValidation' collection and I want:

  • If haven't sent mail before: insert a new record contains mail & code
  • If have sent before: update the code in the existing record

It could be easily done with upsert, but in Phalcon, I should:

  • Find by email

  • If exists ($record != false): modify code and save

  • If not exists ($record == false):

    create a new ODM model, set email, set code and save

Could the process be simplified? (and atom operation)


You have the option of directly accessing the driver and using the update() method of the driver with the upsert option. For example, from within a model's method:

$this->getConnection()->{$this->getSource()}->update($criteria, $new_object, array('upsert' => true))

That approach has the downside that you will need to manually trigger any events, but you get the benefits of the atomic operation.

edited Mar '16

I am sharing sample work here to upsert MONGODB Insert

/ Insert single item into array - Construct input JSON as below / {YourArrayField : 111 }

/ Insert multiple items into array - Construct document as below / {YourArrayField : { <strong>$each:</strong> [ 111, 222, 333 ] } }

/ Insert multiple documents into array / {YourArrayField : { <strong>$each:</strong> [ {OrderID:1, Total:20.00}, {OrderID:2, Total:12.00} ] } }


UPDATE MyCollection SET [properties specified in DOCUMENT] WHERE Country=[input value] AND State=[input value]

To see full article You can follow this link


edited Apr '16

Hello there...

Not familiar with MongoDB but I found a very useful and accurate article of all about MongoDB like Update, Delete and Upsert an More. Here is a link Feel free to visit

Hope it will help... :-)