Mongodb update() vs. findAndModify() performance
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.