Home > Software design >  mongodb $in operator in $expr doesn't use the index
mongodb $in operator in $expr doesn't use the index

Time:10-08

I need documents by several identifiers

It doesn't work(freeze):

db.collection.aggregate([{
    $match: {
        $expr: {
            $in: ['$_id', [4, 6]]
        }
    }
}]);

but it works:

db.collection.find({
    _id: {
        $in: [4, 6]
    }
});

CodePudding user response:

$expr has limitation on index use see this

only $eq, $lt, $lte, $gt, and $gte aggregate operators can use index

In the past even less operators were supported, MongoDB 5.0 added more and probably next versions will add even more.

$in aggregate operator cannot use the index. But if you replace it with

aggregate(
[{"$match":
  {"$expr":{"$or":[{"$eq":[4, "$_id"]}, {"$eq":[6, "$_id"]}]}}}])

It will be fast, and index will be used.
Here you can avoid the need for $expr you can use the $in query operator not the $in aggregate operator, as noted in the comments also.

{ $match: { _id: {$in: [4, 6]} }
  • Related