Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB $addToSet vs $push (speed)

I have a collection of 150 million documents in a database in MongoDB and I want to add an array field to each document (keywords)

{ 
    Subject: "value1", 
    Object: "value2", 
    "keywords": [A,A,B,C,D]
} 

So the field I want to add elements to is "keywords". Should I do addToSet(A) or push(A)? I don't care about duplicates. So the above example is correct. But I only care about speed. which one is faster (time wise) $addToSet or $push ??

like image 552
Hiba Arnaout Avatar asked Sep 29 '22 15:09

Hiba Arnaout


1 Answers

The push() should be faster, because it has not to check for duplicates like addToSet() needs to. There is also a description on how to profile in the documentation if you want to test both methods in a real world like setup.

like image 152
Simulant Avatar answered Oct 03 '22 02:10

Simulant