Clustered collections
A collection sorted by _id that can delete its documents when they expire.
Create a collection sorted by _id that can delete its documents when they expire, without a separate TTL index.
Requirements
- A user with
dbAdminorreadWriteon the database to create collections.
Create
JavaScript
db.createCollection("sessions", { clusteredIndex: { key: { _id: 1 }, unique: true }, expireAfterSeconds: 86400 });With expireAfterSeconds, the _id has to be a date for the document to expire.
Check
In mongosh, db.getCollectionInfos({ name: "sessions" }) shows clusteredIndex and expireAfterSeconds in the
collection options, so you can see that the collection was created ordered by _id and with its expiry.
Common problems
createCollectionfails when you ask for bothcappedandclusteredIndex.