MongoDB/NoSQL: Keeping Document Change History

后端 未结 5 1819
余生分开走
余生分开走 2020-12-02 03:31

A fairly common requirement in database applications is to track changes to one or more specific entities in a database. I\'ve heard this called row versioning, a log table

5条回答
  •  被撕碎了的回忆
    2020-12-02 04:29

    For users of Python (python 3+, and up of course) , there's HistoricalCollection that's an extension of pymongo's Collection object.

    Example from the docs:

    from historical_collection.historical import HistoricalCollection
    from pymongo import MongoClient
    class Users(HistoricalCollection):
        PK_FIELDS = ['username', ]  # <<= This is the only requirement
    
    # ...
    
    users = Users(database=db)
    
    users.patch_one({"username": "darth_later", "email": "darthlater@example.com"})
    users.patch_one({"username": "darth_later", "email": "darthlater@example.com", "laser_sword_color": "red"})
    
    list(users.revisions({"username": "darth_later"}))
    
    # [{'_id': ObjectId('5d98c3385d8edadaf0bb845b'),
    #   'username': 'darth_later',
    #   'email': 'darthlater@example.com',
    #   '_revision_metadata': None},
    #  {'_id': ObjectId('5d98c3385d8edadaf0bb845b'),
    #   'username': 'darth_later',
    #   'email': 'darthlater@example.com',
    #   '_revision_metadata': None,
    #   'laser_sword_color': 'red'}]
    

    Full disclosure, I am the package author. :)

提交回复
热议问题