Reputation: 14125
I currently have a collection with documents like the following:
{ foo: 'bar', timeCreated: ISODate("2012-06-28T06:51:48.374Z") }
I would now like to add a timestampCreated
key to the documents in this collection, to make querying by time easier.
I was able to add the new column with an update
and $set
operation, and set the timestamp value but I appears to be setting the current timestamp using this:
db.reports.update({}, {
$set : {
timestampCreated : new Timestamp(new Date('$.timeCreated'), 0)
}
}, false, true);
I however have not been able to figure out a way to add this column and set it's value to the timestamp of the existing 'timeCreated' field.
Upvotes: 5
Views: 3783
Reputation: 103305
Use updateMany()
which can accept aggregate pipelines (starting from MongoDB 4.2) and thus take advantage of the $toLong
operator which converts a Date into the number of milliseconds since the epoch.
Also use the $type
query in the update filter to limit only documents with the timeCreated
field and of Date type:
db.reports.updateMany(
{ 'timeCreated': {
'$exists': true,
'$type': 9
} },
[
{ '$set': {
'timestampCreated': { '$toLong': '$timeCreated' }
} }
]
)
Upvotes: -1
Reputation: 92559
Do a find for all the documents, limiting to just the id and timeCreated fields. Then loop over that and generate the timestampCreated value, and do an update on each.
Upvotes: 3