theTuxRacer
theTuxRacer

Reputation: 13869

How is "foo" different from foo, in a mongodb key:value pair?

When I see a field:value pair as

"name":"foo" and "name":foo

what is the difference between the two? Are both the values supposed to be strings?

And what about

"age":3 and "age":"3"

Is the first one an integer? I am confused.

Thanks.

Upvotes: 3

Views: 388

Answers (1)

Niels van der Rest
Niels van der Rest

Reputation: 32184

Strings vs. variables

The following assigns the string value "foo" to a property:

item = { "name" : "foo" } // item.name = "foo"

The following assigns the value of the foo variable to a property. If the foo variable doesn't exist, you'll receive an error message:

item = { "name" : foo } // foo doesn't exist yet, will result in error

foo = "my value" // foo is defined here
item = { "name" : foo } // item.name = "my value"

Numbers vs. strings

The following assigns a Number value to a property:

child = { "age" : 3 } // child.age = 3

Numbers can be used in all mathematical operations. For example, child.age * 3 will result in 9 and child.age + 4 will result in 7.

The following assigns a string value to a property:

child = { "age" : "3" } // child.age = "3"

Strings cannot be used in all calculations. For example, child.age * 3 will result in 9, but child.age + 4 will result in 34, due to string concatenation.

You should only use strings if the data is textual data. If the data is numerical, store it as a number (without the quotes).

Upvotes: 5

Related Questions