Jeff Storey
Jeff Storey

Reputation: 57202

unset variable in mongo shell

Is there a way to unset a variable in the mongo shell. For example if I try to reference myvar before defining it, I get ReferenceError: myvar is not defined (shell):1, but once I define it and I'm finished with it, I'd like to return it to that state.

I tried setting it to null and undefined, neither of which worked.

EDIT: When trying the delete operator, I get the following output:

> var myvar = 5
> myvar
5
> delete myvar
false
> 
> myvar
5
> 

Upvotes: 5

Views: 4355

Answers (2)

BrentR
BrentR

Reputation: 928

You can also remove fields in a document stored in a variable. This sample code shows how to remove the field called "oops" from the rectangle document.

> var rectangle = { "length":5, "width":10, "oops":20 }
{ "length":5, "width":10, "oops":20 }

> delete rectangle.oops
true

> rectangle
{ "length":5, "width":10 }

Upvotes: 1

César
César

Reputation: 10119

The mongo shell is an interactive JavaScript shell, so you can use the delete operator:

$ mongo
MongoDB shell version: 2.2.3
connecting to: test
> myvar
Wed Feb 20 12:08:35 ReferenceError: myvar is not defined (shell):1
> myvar = {x: 1}
{ "x" : 1 }
> myvar
{ "x" : 1 }
> delete myvar
true
> myvar
Wed Feb 20 12:08:59 ReferenceError: myvar is not defined (shell):1
> 

Upvotes: 5

Related Questions