Audit logging basics in MongoDB - Time & Space Complexity
Audit logging in MongoDB records actions on the database for security and tracking.
We want to understand how the time to log each action changes as more actions happen.
Analyze the time complexity of this audit logging setup.
db.createCollection("auditLog")
function logAction(action) {
db.auditLog.insertOne({
timestamp: new Date(),
action: action
})
}
// Example usage
logAction("user_login")
This code creates an audit log collection and inserts a log entry for each action.
Look at what repeats when logging many actions.
- Primary operation: Inserting one document into the auditLog collection.
- How many times: Once per action logged, so as many times as actions happen.
Each new action causes one insert operation.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 insert operations |
| 100 | 100 insert operations |
| 1000 | 1000 insert operations |
Pattern observation: The number of operations grows directly with the number of actions logged.
Time Complexity: O(n)
This means the time to log actions grows linearly with how many actions you record.
[X] Wrong: "Logging many actions happens instantly and does not slow down."
[OK] Correct: Each log entry requires a database insert, so more actions mean more inserts and more time.
Understanding how logging scales helps you design systems that keep track of activity without slowing down.
"What if we batch multiple log entries into one insert? How would the time complexity change?"