Reputation: 125
What's the difference in performance of MongoDB if $in
operator is used for a list of values against the querying for each value individually and vice versa.
E.g. if I have a list of some values like values = [a, b, c, d, e, f, g]
then which way of querying would be better ?
option a)
find({value: [$in: values]})
option b)
values.each { val ->
find({value: val})
}
Upvotes: 0
Views: 288
Reputation: 46311
In a nutshell, $in
is very fast unless the array is huge (say a couple of thousand ids from experience, your mileage may vary).
Like @Sammaye already pointed out, there is considerable overhead for each query (network/thread synchronization, serialization of the actual BSON message, network latency, cursor management, etc.) so I'd bet $in
will be faster almost all cases that are relevant in practice. If the array gets huge, it might be better to perform a few larger in
queries instead of one huge in
query though.
Upvotes: 2