$in with one element

Is there any performance advantage to doing

    Query query = new Query();
    if (ids.size() == 1) {
    } else {

versus the simpler approach where we just do query.addCriteria(Criteria.where(ID_FIELD).in(ids));?

In this scenario we have a large amount of data in the table that is being queried (around 300 million documents) and an index on ID_FIELD. I have been looking at the logs and have seen slow queries of the second type, so I’m wondering if it would be worth adding the extra code.

1 Like

Hello @Chris_Gray, Welcome to the MongoDB Community Forum,

You don’t need to create conditional logic in your backend code to choose between $in and $eq based on the number of elements. MongoDB handles this equivalence internally.

You can check executing both queries { $in: ids } and { $eq: ids[0] } with the explain() command, it will parse it in $eq condition,

"parsedQuery": {
  "key": {
    "$eq": "value 1"

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.