Emmet B
Emmet B

Reputation: 5531

Mongodb: add a date field/column to documents which do not have a date field

I have a collection called posts, initially they only had "text" and "author" field. Later I added a "date" field for later posts.

How I can add a date field for initial posts, for those who does not have date/created-at field.

I guess I need to use following two commands, but cant figure out how to make the connection (i.e. loop)?

db.posts.find({"date":{"$exists":false}}
ObjectId(_id).getTimestamp()

Upvotes: 1

Views: 56

Answers (2)

Paul T. Rawkeen
Paul T. Rawkeen

Reputation: 4114

db.posts
  .find({"date":{"$exists":false}) // looking for records without `date` field
  .forEach(function (record) { // iterating through each record
      record.date = null; // if you want to define current date use `new Date()`
      db.posts.save(record); // saving updated record
  });

Upvotes: 3

Bala
Bala

Reputation: 11244

I guess there is a forEach() function that you could use. forEach

db.posts.find({"date":{"$exists":false}).forEach(<function - do something>)

Upvotes: 1

Related Questions