Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb - add index on 'calculated' fields

Tags:

mongodb

I have a query that includes an $expr-operator with a $cond in it. Basically, I want to have objects with a timestamp from a certain year. If the timestamp is not set, I'll use the creation date instead.

{
  $expr: {
    $eq: [
      {
        $cond: {
          'if': {
            TimeStamp: {
              $type: 'null'
            }
          },
          then: {
            $year: '$Created'
          },
          'else': {
            $year: '$TimeStamp'
          }
        }
      },
      <wanted-year>
    ]
  }
}

It would be nice to have this query using a index. But is it possible to do so? Should I just add index to both TimeStamp and Created-fields? Or is it possible to create an index for a Year-field that doesn't really exist on the document itself...?

like image 438
Vegar Avatar asked Sep 12 '25 01:09

Vegar


1 Answers

Not possible

Indexes are stored on disk before executing the query.

Workaround: On-Demand Materialized Views

You store in separate collection your calculated data (with indexes)

like image 189
Valijon Avatar answered Sep 15 '25 17:09

Valijon