Migrating the data type of a nested property

I have a collection of documents in my DB that look roughly like this:

{ 
  "foo": {
    "bar": new ISODate("2020-05-18T14:10:30Z")
  }
}

I want to update all the documents that have a date there by converting the date to a number (milliseconds since epoch).
Here is what I tried:

db.collection.updateMany(
  { "foo.bar": { $type: "date" } },
  [
    { $set: { "foo.bar": { $toLong: "$foo.bar" }}}
  ]
)

Alas, that doesn’t seem to do anything. What am I doing wrong? :slight_smile:
(There are many more properties on both levels, in case that makes a difference…)

Hi @_Christian,

Seemed to have work for me for the following document:

test>db.coll2.find({},{_id:0})
[
 { foo: { bar: ISODate("2020-05-18T14:10:30.000Z") } } 
]
test> db.coll2.updateMany(
   { "foo.bar": { $type: "date" } },
   [
    { $set: { "foo.bar": { $toLong: "$foo.bar" }}}
   ]
)

Output after the update:

test> db.coll2.find({},{_id:0})
[
  {
    foo: { bar: Long("1589811030000") }
  }
]

What was the output from running the updateMany()? Did you receive any value > 0 for matchedCount and/or modifiedCount?

Can you also provide sample document(s) that you expect to be updated as well as the MongoDB version you’re running?

I could be missing something obvious but good to get those pieces of information as well :slight_smile:

Regards,
Jason

Hi Jason,

Thanks for having a look and trying this for me.
Turns out that for that one statement, I had literally written “collection” instead of the collection’s actual name. :man_facepalming:
I’m using IntelliJ to run these from its DB Console window; sadly it just reports

[date-time] completed in xyz ms

in either case. No mention of affected documents. Which is a bit unhelpful, really…
But it’s all working now; types converted successfully. :slight_smile:

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.