2

I'm trying to change a type string to an Integer. The following code selects the right element when simply searching and the code works perfectly for string elements at the top.

db.providers.find({'assignments.assignment' : 
    {$elemMatch :
        {
            as_total_hours : 
                {$exists : true}}}}).forEach( function(obj) { 
                    obj.as_total_hours = parseInt(obj.as_total_hours); 
                    db.providers.save(obj); 
                })

Here is a sample of the document.

"dev_active_interviews" : 0,
"assignments" : {
    "assignment" : [ 
        {
            "as_rate" : "$3.89",
            "as_from" : "05/2011",
            "as_to"   : "Present",
            "as_total_hours " : "16"
        },
        {
            "as_rate" : "$2.22",
            "as_from" : "11/2010",
            "as_to"   : "Past",
            "as_total_hours" : "200"
        }
     ]
  }

1 Answer 1

3

Your code is assuming that the find returns the embedded assignment objects rather than the object.

Change :

obj.as_total_hours = parseInt(obj.as_total_hours);
db.providers.save(obj); 

to

obj.assignments.assignment.forEach(function(obj) {
    obj.as_total_hours = parseInt(obj.as_total_hours);
})
db.providers.save(obj); 

You could also change the {$exists:true} to {$type: 2} (or combine them) so that the query only finds strings.

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

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.