How to unset a variable in MongoDB shell?

Use the delete operator to unset (remove) a variable from the MongoDB shell environment. This permanently removes the variable from memory.

Syntax

delete variableName;

Example 1: Check Undefined Variable

First, let's check if a variable exists before defining it ?

customerDetail;
2019-05-08T22:29:17.361+0530 E QUERY [js] ReferenceError: customerDetail is not defined :
@(shell):1:1

Example 2: Define and Use Variable

Now let's create the variable with a value ?

customerDetail = {"CustomerFirstName": "Chris"};
{ "CustomerFirstName" : "Chris" }

Display the variable value ?

customerDetail;
{ "CustomerFirstName" : "Chris" }

Example 3: Unset the Variable

Use delete to remove the variable from memory ?

delete customerDetail;
true

Example 4: Verify Variable is Removed

Try accessing the variable again to confirm it's undefined ?

customerDetail;
2019-05-08T22:30:35.530+0530 E QUERY [js] ReferenceError: customerDetail is not defined :
@(shell):1:1

Key Points

  • delete returns true when the variable is successfully removed.
  • Accessing a deleted variable throws a ReferenceError.
  • This only affects shell session variables, not database collections or documents.

Conclusion

The delete operator permanently removes variables from the MongoDB shell memory. Use it to clean up unwanted variables during your shell session.

Updated on: 2026-03-15T01:06:18+05:30

683 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements