skip to Main Content

I have a document as follows:

{
    "_id": "1234",
    "created_at": 1678787680
}

I want to modify the document and add a new key updated_at which will be a datetime equivalent of the created_at UNIX timestamp.

{
    "_id": "1234",
    "created_at": 1678787680,
    "updated_at": "2023-03-14 15:39:18.767232"
}

Is there a way to perform this operation using updateMany?

2

Answers


  1. Try this one:

    db.collection.aggregate([
       { $set: { updated_at: { $toDate: { $multiply: ["$created_at", 1000] } } } }
    ])
    
    Login or Signup to reply.
  2. Use $toDate. You are better off storing dates as proper BSON date types (not as strings in your example).

    mongosh:

    db.mycollection.updateMany({}, [{'$set': {'updated_at': {'$toDate': {'$multiply': ['$created_at', 1000]}}}}])
    

    pymongo:

    db.mycollection.update_many({}, [{'$set': {'updated_at': {'$toDate': {'$multiply': ['$created_at', 1000]}}}}])
    

    full example:

    from pymongo import MongoClient
    
    db = MongoClient()['mydatabase']
    
    
    db.mycollection.insert_one({
        "_id": "1234",
        "created_at": 1678787680
    })
    
    db.mycollection.update_many({}, [{'$set': {'updated_at': {'$toDate': {'$multiply': ['$created_at', 1000]}}}}])
    print(db.mycollection.find_one())
    

    prints:

    {'_id': '1234', 'created_at': 1678787680, 'updated_at': datetime.datetime(2023, 3, 14, 9, 54, 40)}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search