0
0
MongoDBquery~5 mins

Audit logging basics in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Audit logging basics
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

Each new action causes one insert operation.

Input Size (n)Approx. Operations
1010 insert operations
100100 insert operations
10001000 insert operations

Pattern observation: The number of operations grows directly with the number of actions logged.

Final Time Complexity

Time Complexity: O(n)

This means the time to log actions grows linearly with how many actions you record.

Common Mistake

[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.

Interview Connect

Understanding how logging scales helps you design systems that keep track of activity without slowing down.

Self-Check

"What if we batch multiple log entries into one insert? How would the time complexity change?"