Search code examples
mongodbindexingsparse-matrixttl

MongoDB TTL sparse index?


Can you TTL a sparse field? If so, should you declare the TTL index sparse? Like so?

db.eventlog.createIndex( { "lastModifiedDate": 1 }, { expireAfterSeconds: 3600 , sparse:"true"} )

Solution

  • > use foo
    switched to db foo
    > db.foo.createIndex({date: 1}, {expireAfterSeconds: 5, sparse: true})
    {
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
    }
    
    > db.foo.getIndexes()
    [
        {
            "v" : 1,
            "key" : {
                "_id" : 1
            },
            "name" : "_id_",
            "ns" : "foo.foo"
        },
        {
            "v" : 1,
            "key" : {
                "date" : 1
            },
            "name" : "date_1",
            "ns" : "foo.foo",
            "expireAfterSeconds" : 5,
            "sparse" : true
        }
    ]
    
    > db.foo.insert({date: new Date()})
    
    > db.foo.find()
    { "_id" : ObjectId("5841aeb650b5412e92ebbb9b"), "date" : ISODate("2016-12-02T17:26:14.617Z") }
    
    > db.foo.find()
    >
    

    It appears that this worked fine. Note that according to the documentation , the TTL operation fires every 60 seconds or so, so the expireAfterSeconds: 5 may take longer.