5

I want to create a partial index in MongoDB which excludes documents that are older than 30 days in the past from the current date.

Something like this (pseudo code):

partialFilterExpression: { date: { $gte: { $currentDate - 30 days }} }

The $currentDate should be the actual current date, in other words the date is a dynamic value, not a static value.

It this possible?

2 Answers 2

6

As far as I know, dynamic values in the filter expression are not currently supported with partial indexes & the filter expression only supports a subset of regular mongo query operators (and that subset does not include the $date operator).

One way to approximate your desired behavior is by creating a shouldIndex boolean field on your documents, have {shouldIndex: true} be your filter expression, and have a script update that field once a day for documents that are older than current_date - 30.

1
  • I am tempted to mark this as correct, but I'll wait a bit maybe there are other ideas.
    – Manuel
    Sep 10, 2019 at 13:28
-1

Yes that's possible,

you can use normal createIndex operation with partialFilterExpression which contains you condition.

I think code in you quenstion will only work

You can use

let today = new Date();    //your date condition

db.collection_name.createIndex({ field1 : type1, field2: type2},
            partialFilterExpression: { date: { $gte: { today }} })

Read more about parital indexes here,

however it comes with some restrictions too.

4
  • Looks like today will be the static value of the time of index creation.
    – Manuel
    Sep 7, 2019 at 16:46
  • No, today will be the date when you will be running your script. Sep 7, 2019 at 16:52
  • 2
    The script will only run once to create the index. Today will have the value of the time when the script ran. That value will not change anymore.
    – Manuel
    Sep 7, 2019 at 16:59
  • Okay, you want that, if new Documents are getting inserted then this filter should also be applied on them too! Sep 7, 2019 at 17:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.