Search code examples
pythonmongodbmongodb-queryaggregation-frameworkpymongo

How to add a key in a mongo document on the basis of an existing key?


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?


Solution

  • 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)}