Search code examples
mongodbindexingttl

MongoDB creating index on a new field


I need to create a TTL Index in MongoDB and for that, I'm adding a new field "last_modified". I'm using the latest Python and pymongo in case this makes any difference. After reading information on sparse and non-sparse indexes I understand that all documents that do not have "last_modified" will have this field added with the null value.

Is there a way to set some default value instead of null for those documents?

Alternatively, I'll have to update all documents in all DB instances using some migration function, but I would really like to do it clean...

Thanks in advance for any links or ideas!


Solution

  • I understand that all documents that do not have "last_modified" will have this field added with the null value.

    No this is not true, sparse indexes just index documents where the field exists. documents without this field will just be out of the index converage.

    Is there a way to set some default value instead of null for those documents? ... I'll have to update all documents in all DB instances ... to do it clean...

    You have to run an update, there is no magic solution. Not sure why doing this is "not clean".

    The update is super simple:

    // this query will allow you to execute the update even if you started streaming new events with this field.
    db.collection.updateMany({ last_modified: {$exists: false} }, { $set: { last_modified: defaultValue }})