Darth Shekhar
Darth Shekhar

Reputation: 125

Efficiency of MongoDB $in operator on indexed fields

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

Answers (1)

mnemosyn
mnemosyn

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

Related Questions