2

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 !

8
  • Can you make your question little more clearer? What exactly do you mean by at the end I would like to add fields ? Commented Aug 8, 2016 at 9:19
  • 1
    I try on dummy data to add field. Now I'm working on the real set. So i know how to add a field on the whole document, but how to : 1) Add field only if this field is not present. 2) Add a default value : here Data.now() Is that more clear for you ? Commented Aug 8, 2016 at 9:22
  • 1
    From Mongo Doc : Optional. If set to true, creates a new document when no document matches the query criteria. The default value is false, which does not insert a new document when no match is found. I don't want a new document but a new field on each. Commented Aug 8, 2016 at 9:26
  • 1
    Yes I want to keep track of when I put this data on the DB and if an update happend keep track when was the last modification. Commented Aug 8, 2016 at 9:30
  • 1
    Okay, then may be you need to keep two fields one on create at(ca), and other on update at(ua). Created at will be updated only on create. Later on update, always update ua field may be. Commented Aug 8, 2016 at 9:31

1 Answer 1

1

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})
Sign up to request clarification or add additional context in comments.

7 Comments

So in my case : db.test.update({created:{$exists:false}}), {$set: {"created":new Date}}, {upsert:false, multi:true})
Here i am considering you are updating ca(created at ) field for all the documents from mongo cli. So when it has ca already it wont update.
Is it this is what you need? Or some thing else?
Do I have to do 2 different .update() or I can put the 2 fields in on request ?
No I'm writing an API (Node + Express) with all the needed route. I know how to programmatically update but I want to import the first batch, other gonna come later.
|

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.