Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Create MongoDB indexes for: sessions that should be deleted 30 minutes after lastSeen; unique emails only for active users; and a search by any element of a tags array. Show the commands.

Sessions get a TTL index, db.sessions.createIndex({lastSeen: 1}, {expireAfterSeconds: 1800}), and a background task deletes documents once lastSeen is more than 30 minutes old, checking about every 60 seconds, so deletion is not exact. Unique emails for active users use a partial unique index, db.users.createIndex({email: 1}, {unique: true, partialFilterExpression: {status: 'active'}}), and only queries that include the filter condition can use it. Searching by any tag is a normal index on the array, db.articles.createIndex({tags: 1}), which MongoDB makes multikey with one entry per element; a compound index may include at most one array field per document.

Why this question is asked

These three requirements come up in almost every real application: sessions that must expire, uniqueness rules that apply only to some records, and tag search. MongoDB solves each with a specific index feature, and each feature has a detail that surprises people in production: TTL is not instant, a partial index is invisible to queries that do not mention its filter, and array indexes have limits on combining arrays. Interviewers ask for the commands and then probe those details. In this answer, we will write each index, see how it behaves with a small example, and explain the catch that comes with it.

1A Quick Recap of Index Options

createIndex takes a key pattern, such as {lastSeen: 1}, and an options document. The options change what the index does beyond speeding up queries. expireAfterSeconds turns an index into a TTL index, short for time to live, that removes old documents. unique makes the index reject duplicate keys. partialFilterExpression limits the index to documents that match a condition. And when the indexed field holds an array, MongoDB automatically makes the index multikey, without any option.

2Sessions Deleted 30 Minutes After lastSeen

A TTL index is a single-field index on a date field with an expiry in seconds.

Java
db.sessions.createIndex({ lastSeen: 1 }, { expireAfterSeconds: 1800 });
db.sessions.insertOne({ _id: "s1", userId: 42, lastSeen: new Date() });
// every request refreshes the session, pushing its expiry forward
db.sessions.updateOne({ _id: "s1" }, { $set: { lastSeen: new Date() } });
// 30 minutes after the last update, plus up to about a minute:
db.sessions.findOne({ _id: "s1" }); // null

A background task on the primary, the TTL monitor, wakes up about every 60 seconds and deletes documents whose lastSeen plus 1,800 seconds is in the past. Notice the catch: deletion is not exact. A session can survive a minute or more beyond its expiry, longer if the server is busy or a large number of documents expire at once. So the application must never trust that a document in sessions is valid; it should also check lastSeen when it reads the session.

Two more details are worth knowing. The field must hold a BSON date, or an array of dates, in which case the earliest one counts; a document with a string or missing lastSeen never expires. And the deletes replicate like normal deletes, so a sudden expiry of millions of documents is real write load.

3Unique Emails Only for Active Users

Users who closed their account should be able to leave their email behind so someone, or they themselves, can register it again. A plain unique index on email would forbid that. A partial unique index enforces uniqueness only among documents that match the filter.

Java
db.users.createIndex(
{ email: 1 },
{ unique: true, partialFilterExpression: { status: "active" } }
);
db.users.insertOne({ email: "ana@example.com", status: "closed" }); // ok
db.users.insertOne({ email: "ana@example.com", status: "active" }); // ok
db.users.insertOne({ email: "ana@example.com", status: "active" });
// E11000 duplicate key error: only one active user per email
db.users.find({ email: "ana@example.com", status: "active" }); // uses the partial index
db.users.find({ email: "ana@example.com" }); // cannot use it: COLLSCAN

Only active documents are in the index, so two closed accounts with the same email do not conflict, but a second active one does. The catch is on the query side. Because the index does not contain every document, MongoDB can only use it when the query's filter guarantees that every matching document is in the index.

The second query might match a closed account, which is not in the index, so MongoDB must look elsewhere. In practice we include status: 'active' in the login query, or add a separate non-unique index on email for lookups across all users. Another detail: a partial index is better than the older sparse option here, because sparse only skips documents where the field is missing, not documents in a particular state.

4Searching by Any Element of a tags Array

For tags we write an ordinary index. When MongoDB sees that tags holds arrays, it marks the index as multikey and stores one index entry per element of the array.

Java
db.articles.createIndex({ tags: 1 });
db.articles.insertOne({ _id: 1, title: "Kafka basics", tags: ["kafka", "java", "streams"] });
// index entries: "java" -> 1, "kafka" -> 1, "streams" -> 1
db.articles.find({ tags: "java" }); // any element equals "java"
db.articles.find({ tags: { $all: ["java", "kafka"] } }); // both tags
// explain: IXSCAN { tags: 1 }, isMultiKey: true
The three indexes at a glance
RequirementIndex optionThe detail to remember
Expire sessions after 30 minutesexpireAfterSeconds: 1800removed by a task about every 60 s, not exactly on time
Unique email among active usersunique plus partialFilterExpressionqueries must include status: 'active' to use it
Find articles by any tagplain index on an array fieldmultikey: one entry per element

So a query for one tag is a simple index lookup, and the article with three tags costs three index entries. That is why huge arrays make expensive indexes: a document with 10,000 elements adds 10,000 entries and rewrites them on change.

5The Limit on Arrays in Compound Indexes

A compound multikey index can include several fields, but for any single document at most one of the indexed fields may be an array. The reason is size: if both fields were arrays, MongoDB would need an entry for every combination of elements, the Cartesian product, which could explode.

Java
db.articles.createIndex({ tags: 1, publishedAt: -1 }); // fine: one array field
db.articles.createIndex({ tags: 1, authors: 1 });
db.articles.insertOne({ tags: ["java", "kafka"], authors: ["ana", "raj"] });
// error: cannot index parallel arrays [authors] [tags]

So {tags: 1, publishedAt: -1} works and serves 'newest articles with tag java', but an index on two array fields fails as soon as a document has arrays in both. If we need both, we create two separate indexes and let each query use the one it needs.

6Follow-up questions

Can a TTL index expire each document at its own time?

Yes. Create the index with expireAfterSeconds: 0 on a field like expiresAt, and set that field to the exact expiry date in each document. The monitor then deletes each document once its own expiresAt has passed, still with the same delay of up to about a minute.

Can a TTL index be compound?

Historically TTL indexes had to be single-field; compound TTL indexes are not supported, so check your version's documentation. The common workaround is a separate single-field TTL index alongside any compound index we need.

Does the multikey index help with $elemMatch on subdocuments?

Yes, an index on an array of subdocuments, such as {'items.sku': 1}, is multikey too, and queries using $elemMatch or dotted paths can use it. For conditions on two fields of the same element, a compound index on both subfields plus $elemMatch keeps the conditions on one element.

7Conclusion

In this answer, we wrote three index commands. A TTL index on lastSeen with expireAfterSeconds 1800 removes stale sessions, though the background task runs about every 60 seconds so deletion is approximate. A partial unique index on email with a filter on status enforces uniqueness only for active users, and queries must include that condition to use it. An ordinary index on tags becomes multikey with one entry per element, and a compound index may contain at most one array field per document.

What to say in the interviewAbout 90 seconds aloud

Open with

For sessions I would create a TTL index: createIndex on lastSeen ascending with expireAfterSeconds 1800. Each request updates lastSeen, and a background TTL task on the primary deletes documents whose lastSeen is more than thirty minutes old.

Then, if they want more

It runs about every sixty seconds, so deletion is not exact, and the application should still check lastSeen when it reads a session. The field has to be a real date, otherwise it never expires. For emails I would use a partial unique index: createIndex on email with unique true and a partialFilterExpression of status active.

Only active users are in the index, so a closed account can share an email with a new active one, but two active users cannot.

The catch is that a query can only use a partial index if its filter includes the partial condition, so the login query should include status active, or I add a separate index for lookups across all users. For tags I just create an index on tags.

Because the field is an array, MongoDB makes it multikey with one entry per element, so finding articles with tag java is an index lookup. The limit to remember is that a compound index can include at most one array field per document, because otherwise it would need an entry for every combination.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
MongoDB manual
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Create MongoDB indexes for: sessions that should be deleted 30 minutes after lastSeen...": https://scrivio-interview-library.netlify.app/databases/mongodb/c234636680/