Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Which would be faster? Regex search on string or direct search on array?

My application currently performs a regex search on a text field which is a comma separated Objectids. According to Mongodb documentation, Mongo uses indexes while doing regex searches.

My initial thought was to use an array to store the ObjectIds instead of using the string. But will the array search have better performance than the regex search since both are using indexes?

like image 820
I-am-batman Avatar asked Dec 28 '25 18:12

I-am-batman


1 Answers

Using an array of ObjectIds instead of a comma-separated list of ObjectId strings is the way to go here.

  1. An array will use less space: an ObjectId string is 24 characters while a BSON ObjectId is 12 bytes.
  2. An array index is more effective: for a regex search that isn't rooted to the beginning of the text (i.e. not starting with ^), the entire index must be searched O(n) while with an array, each element has its own multikey index entry O(log n).
  3. The size of an index entry must be less than 1024 bytes, which would limit you to about 42 ObjectIds in a text field.
  4. Array elements are atomically modifiable: you can use array update operators to directly modify individual elements.
like image 171
JohnnyHK Avatar answered Dec 31 '25 11:12

JohnnyHK



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!