Index on $filter

Hello,

I would like to know if I have to create index for nested array object field (replyToId) if I use it only together with $project and $filter;

for example:

{
                    $project: {
                        _id: 1,
                        replies: {
                            $filter: {
                                input: `$comments`,
                                as: 'comment',
                                cond: {
                                    $eq: [`$$comment.replyToId`, new ObjectId(data.commentId)],
                                },
                            },
                        },
                    },
                },

Indexes are mostly useful to find documents fast when querying - projection is something done to already found documents and therefore an index cannot help here (other than in some cases where a covered index query can help you avoid fetching the document entirely but this isn’t one of those cases).

TL;DR no, you don’t need to create an index for this field unless you are also querying by it.

Asya

3 Likes