Maria
Maria

Reputation: 3525

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!

Upvotes: 3

Views: 3263

Answers (1)

womp
womp

Reputation: 116987

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.

Upvotes: 3

Related Questions