MongoDB expireAfterSeconds does not delete documents

I would like MongoDB to clear data from its collections after skipping% seconds. I set the index, but the collection does not clear after a while, all 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()
};

History of the collection, 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
    }
]

An additional question related to creating indexes.

Now it may happen that two records have the same value created, and because of this, mongo now throws an error from the collection of duplicate keys E11000.

Is it possible to add created and expireAfterSeconds, but it is not necessary to create uniq?

+4
source share
2 answers

MongoDB:

TTL . TTL.

_id: 1 created, ,

+5

TTL . TTL. :

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

, , , , .

+1

Source: https://habr.com/ru/post/1626524/


All Articles