Ragnar
Ragnar

Reputation: 2690

MongoDB - Add timestamp to document with default value

I use mongoimport to put data in my mongodb. The original data don't have timestamp and I would like to keep track of created and updated value.

I try to add a field from the mongo CLI and it works with : db.test.update({}, {$set : {"foo":1}}, {upsert:false, multi:true})

But at the end I would like to add fields above (created updated) with a default: Date.now() if the fields doesn't exist in case of importing another batch of data.

I can figure it out. Or if you have another way to do this. Thanks !

Upvotes: 2

Views: 1936

Answers (1)

jerry
jerry

Reputation: 745

Say you want to add field ca:new Date only if its not present, then on updating use

db.test.update({ca:{$exists:false}}, {$set : {"ca":new Date}}, {upsert:false, multi:true})

Upvotes: 1

Related Questions