Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb update() vs. findAndModify() performance

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!

like image 870
Maria Avatar asked Apr 29 '26 18:04

Maria


1 Answers

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.

like image 55
womp Avatar answered May 01 '26 08:05

womp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!