Auto populate date in MongoDB on insert

后端 未结 4 1258
说谎
说谎 2021-01-05 03:54

MongoDB provides a way to update a date field by the system on update operations: https://docs.mongodb.com/manual/reference/operator/update/currentDate/. Is there any equiva

4条回答
  •  悲&欢浪女
    2021-01-05 04:29

    Since mongo 3.6 you can use 'change stream': https://emptysqua.re/blog/driver-features-for-mongodb-3-6/#change-streams

    to use it you need to create a change stream object by the 'watch' query:

    def update_ts_by(change):
        update_fields = change["updateDescription"]["updatedFields"].keys()
        print("update_fields: {}".format(update_fields))
    
        collection = change["ns"]["coll"]
        db = change["ns"]["db"]
        key = change["documentKey"]
    
        if len(update_fields) == 1 and "update_ts" in update_fields:
            pass
        else:
            client[db][collection].update(key, {"$set": {"update_ts": datetime.now()}})
    
    
    client = MongoClient("172.17.0.2")
    db = client["Data"]
    
    change_stream = db.watch()
    
    for change in change_stream:
        print(change)
        update_ts_by(change)
    

    Note, to use the change_stream object, your mongodb instance should run as 'replica set'. It can be done also as a 1-node replica set (almost no change then the standalone use): Mongo DB - difference between standalone & 1-node replica set

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题