skip to Main Content

I have a MongoDb database with around 1000 records, I had the timestamp option set to false and none of them has the createdAt and updatedAt attributes. Now i’ve set the timestamp to true and I want to update all the objects with createdAt timestamp to match a value within the object that is under date attribute, is that possible?

For example:

Review.findMany({}, $set: { createdAt: '<OBJECT>.date' }});

I want to update the createdAt with the value of the same object in date field.

2

Answers


  1. Chosen as BEST ANSWER

    Found the solution

    So what I wanted to achieve in the first place was just to add createdAt attribute to all documents. The reason I want to do this manually is because I forgot to add the timestamp key to the Scheme, and already have around 1000 records in database.

    This is what I did:

    1. Created a new attribute in my object's Scehma called createdDate. (JavaScript)

    2. Iterating all documents and updating the createdDate to the date (After conversion from date).

    3. Connecting to Database using Mongo Shell (Assisted by this link).

    4. Navigating to the collection I want to edit.

    5. Renaming createdDate to createdAt with this command:

      db.COLLECTION.updateMany({}, { $rename: { 'createdDate': 'createdAt' } })
      
    6. Removing createdDate from Schema.

    Hope it helps someone!


  2. Try this one:

    db.collection.updateMany(
      { createdAt: { $exists: false } },
      [ { $set: { createdAt: { $toDate: "$_id"} } } ]
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search