Clustered collections

Sorted by _id, a clustered collection 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 dbAdmin or readWrite on 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

  • createCollection fails when you ask for both capped and clusteredIndex.

See also