1

In MySQL for example you have data types such as varchar, int, etc. I googled and found http://docs.mongodb.org/manual/core/document/#bson-types page. It seems like with string you just use '' or "". Integers seem to be automatically recognized without specifing the type. How would inserting something like this into mongoDB collection in Perl look like?

Example:
{
 "Name" : "John"
 "Age" :   20
 "Weight" : 180.5
 "Dateofbirth" : 01/01/1990
}

The reason why I want data type specified in the db is that I can use operators to compare numbers for example. If it is text I cannot do that. So far I am thinking in Perl:

$my_collection->insert({
                        'Name' : "$Name",
                        'Age'  : $age,
                         'Weight':$weight,
                         'Dateofbirth': $datevar, 
                       } );

In the above code I am not sure how to specify the data type. For example to tell Weight is Double not integer or string.

2 Answers 2

1

For numeric types, the Perl MongoDB driver will go by whatever Perl thinks the number is. Perl has an internal flag for keeping track of whether something is a float or an int. The MongoDB driver will use 32 or 64-bit ints depending on your platform. If it looks like a string to Perl, it will be stored as a string in MongoDB.

For date types, you need to wrap the date in a DateTime object, or DateTime::Tiny if you use the dt_type attribute.

Sign up to request clarification or add additional context in comments.

7 Comments

so it makes no difference how I use "$age" vs $age in $my_collection->insert statement? I was thinking that is how MongoDB driver knows to treat the field as string or number by that double or single quotes.
Perl could think the number is a string. For JSON encoding, I have a habit of always adding "0" to a number first.
@DoodleKana, the MongoDB driver doesn't know about whether you used double quotes or not. It just gets an *SV (scalar value) structure, and uses the Perl API to find out if Perl thinks it's a string or a number.
Unfortunately this isn't a full answer - for example, if a person had a Weight of 180 instead of 180.5, I see no way to coerce it to a float (SvNOK) except adding 1e-50 to it or something.
@KenWilliams, yes, sadly forcing an IV or PV to NV is rather difficult. I don't know of a good or idiomatic way to do it.
|
1

Use the looks_like_number parameter in the Perl MongoDB driver

use MongoDB::BSON $MongoDB::BSON::looks_like_number = 1;

https://metacpan.org/pod/MongoDB::BSON#looks_like_number

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.