2

I have a document like this:

{
  Name : val
  AnArray : [
     { 
        Time : SomeTime
     },
     {
        Time : AnotherTime
     }
     ...arbitrary more elements
}

I need to update "Time" to a Date type (right now it is string)

I would like to do something psudo like:

foreach record in document.AnArray { record.Time = new Date(record.Time) }

I've read the documentation on $ and "dot" notation as well as a several similar questions here, I tried this code:

db.collection.update({_id:doc._id},{$set : {AnArray.$.Time : new Date(AnArray.$.Time)}});

And hoping that $ would iterate the indexes of the "AnArray" property as I don't know for each record the length of it. But am getting the error:

SyntaxError: missing : after property id (shell):1

How can I perform an update on each member of the arrays nested values with a dynamic value?

1 Answer 1

3

There's no direct way to do that, because MongoDB doesn't support an update-expression that references the document. Moreover, the $ operator only applies to the first match, so you'd have to perform this as long as there are still fields where AnArray.Time is of $type string.

You can, however, perform that update client side, in your favorite language or in the mongo console using JavaScript:

db.collection.find({}).forEach(function (doc) {
       for(var i in doc.AnArray)
       {
          doc.AnArray[i].Time = new Date(doc.AnArray[i].Time);
       }
       db.outcollection.save(doc); 
})

Note that this will store the migrated data in a different collection. You can also update the collection in-place by replacing outcollection with collection.

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

2 Comments

Can I just call ISODate("My iso Date string") and set it to the time variable? Look good in the console but not sure it will use it as a true "Date" type
yes, that's ok. Actually, I expected the string to be in that (ISO 8601) format. The string you posted looks fine, works with the script on my machine, MongoDB 2.5.0

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.