3

For a constantly growing document, I have the choice of using either update() or findAndModify() to insert new elements in an array field. However, findAndModify() will generate cleaner code in my specific application. But I can achieve the same functionality using update(), just more messy.

I'm just wondering how much is the performance gain by using update() instead of findAndModify(). Thanks a lot!

Cœur
  • 37,241
  • 25
  • 195
  • 267
Maria
  • 3,455
  • 7
  • 34
  • 47
  • 1
    The doc has [some comparison between both functions](http://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/#comparisons-with-the-update-method). Usually the key points to make your decision are _"Does the client need to read the document or only to modify it ?"_ and _"Does the client need to specify some order to update one specific document when there are multiple matches ?"_ – Sylvain Leroux Jul 07 '15 at 16:48

1 Answers1

3

I ran a quick test using the mongo shell. For this document:

{
   "c" : 50,
   "growingArray" : [ 0 ]
}

I ran two tests:

for (i = 1; i < 10000; i++)
{
    db.testids.update( { "c" : 50 }, { $addToSet : { "growingArray" : i } } );
}

Took a total of 40.926s on my mid-range laptop.

The findAndModify() version:

for (i = 1; i < 10000; i++)
{
    db.testids.findAndModify({ query: { "c" : 50 }, update : { $addToSet : { "growingArray" : i } } } );
}

took 42.445 seconds. I averaged five runs of each.

Take from it what you will. The knee-jerk conclusion is that you have about a 3% to 4% overhead with findAndModify() in my particular environment with nothing else going on. Keep in mind though that findAndModify() obtains write locks so you could have a much greater impact on performance of your application overall.

womp
  • 115,835
  • 26
  • 236
  • 269
  • Very persuading theory and test result, I think if you are saving some critical data, it is worth to spend a little more time with `findAndModify()` . – Wayne Wei Nov 26 '19 at 05:47