简体   繁体   中英

MongoDB expireAfterSeconds doesn't remove documents

I would like that MongoDB clears data from its collections after %seconds pass. I am setting index, but collection doesn't gets cleared after a while, all the documents are still present.

What am I doing wrong?

DB Version: 3.2

Setting Index:

 db.collection('history').ensureIndex(
   { '_id': 1, 'created': 1 },
   { unique: true, background: true, w: 1, expireAfterSeconds: 60}
 );

// or

 db.collection('history').createIndex(
   { '_id': 1, 'created': 1 },
   { unique: true, background: true, w: 1, expireAfterSeconds: 60}
 );

// history document
var _history = {
  _id: new ObjectId(),
  created: new Date()
};

Collection history, index:

var historyCollectionIndex = [
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "guardian_dev.history"
    },
    {
        "v" : 1,
        "unique" : true,
        "key" : {
            "_id" : 1,
            "created" : 1
        },
        "name" : "_id_1_created_1",
        "ns" : "guardian_dev.history",
        "background" : true,
        "expireAfterSeconds" : 60
    }
]

Additional question that is connected to creating indexes.

Now, it can happen that two entries have the same created value, and because of this, mongo is now throwing an error of E11000 duplicate key error collection.

Is it possible to add created and expireAfterSeconds, but created doesn't have to be uniq?

According to the MongoDB site :

The TTL index is a single field index. Compound indexes do not support the TTL property.

If you remove the _id: 1 index and instead just use created then it should behave as you expect

According to the documentation , the TTL index is a single field index. Compound indexes do not support the TTL property. You should create the index as follows:

db.collection('history').ensureIndex(
{'created': 1 },
{ unique: true, background: true, w: 1, expireAfterSeconds: 60}
);

I have tested it and this index, unlike the one in your question, clears out the records correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM