Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between find_one_and_update() and update_one() in PyMongo for MongoDB?

Here are the references for:

  • find_one_and_update method

Finds a single document and updates it, returning either the original or the updated document.

  • update_one method

Update a single document matching the filter.

It seems to me both of them first query the selected document, then update it.

I would like to know if there is some kind of optimization difference. The only other difference is in the return value, which makes me wonder why one would even use update_one() at all.

like image 976
Nicolò Gasparini Avatar asked Aug 23 '18 15:08

Nicolò Gasparini


1 Answers

There are some changes between that two operations:

  • find_one_and_update

By default :meth:find_one_and_update returns the original version of the document before the update was applied. To return the updated version of the document instead, use the return_document option.

You can limit the fields returned with the projection option.

The upsert option can be used to create the document if it doesn't already exist.

If multiple documents match filter, a sort can be applied.

So this method do a kind of find operation that allows you to sort and filter records in your database.

  • update_one

With this method you can't sort your records, it just does a find operation and update each found elements with a for cycle.

So at the end i think the update_one operation is faster than the find_one_and_update operation.

like image 187
Samuel Roberto Avatar answered Sep 23 '22 15:09

Samuel Roberto