V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
cpj
V2EX  ›  Python

服务器后端只保存一天最后一条信息

  •  
  •   cpj ·
    cpj001 · 2018-09-25 10:34:23 +08:00 · 2404 次点击
    这是一个创建于 2012 天前的主题,其中的信息可能已经有所发展或是发生改变。
    数据是保存到 mongodb,希望保存某条数据时,只保存一天最后一条。我想到的是,保存每条数据之前,按创建时间的字段,查询所有记录并删除。不知道有没有更好的做法
    12 条回复    2018-09-25 11:38:10 +08:00
    MyPassWordis
        1
    MyPassWordis  
       2018-09-25 10:38:42 +08:00
    日期为主键然后 insert ?
    simonliu2018
        2
    simonliu2018  
       2018-09-25 10:38:42 +08:00
    把数据库的主键设计成日期,比如:2018 年 09 月 25 日,如果发现有记录就更新,没有就新增。

    可以再优化一下主键,时间戳的精度是秒,如果把时间戳除一天的秒数( 86400 ),也相当于是当天的日期。
    cpj
        3
    cpj  
    OP
       2018-09-25 10:41:51 +08:00
    @MyPassWordis 可以
    cpj
        4
    cpj  
    OP
       2018-09-25 10:45:26 +08:00
    @simonliu2018 实际保存了不同用户的不同项目的不同信息,如果日期设为主键,是不是数据库只存一个人的了?
    rust
        5
    rust  
       2018-09-25 10:49:19 +08:00
    @cpj 那你用 DateTIme+UserName 做主键不就行了
    cpj
        6
    cpj  
    OP
       2018-09-25 10:50:00 +08:00
    @MyPassWordis 但是我存了不同用户的信息,日期做主键那只能存一个人的了
    cpj
        7
    cpj  
    OP
       2018-09-25 10:51:04 +08:00
    @rust 傻了,是呀,谢谢 ; )
    est
        8
    est  
       2018-09-25 10:59:12 +08:00
    upsert {date: "2018-09-25"}, {value: "text text"}
    loveCoding
        9
    loveCoding  
       2018-09-25 11:01:39 +08:00
    别物理删除,改下记录状态就好,其他随便你怎么弄
    toyuanx
        10
    toyuanx  
       2018-09-25 11:15:22 +08:00
    MongoDB 不知道怎么弄,但是 mysql 可以把 uid+date 设置为唯一索引,然后 insert...on duplicate key update
    cpj
        11
    cpj  
    OP
       2018-09-25 11:37:31 +08:00
    @est 也可行诶
    cpj
        12
    cpj  
    OP
       2018-09-25 11:38:10 +08:00
    @toyuanx 嗯,正准备用这个方案
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5433 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 08:47 · PVG 16:47 · LAX 01:47 · JFK 04:47
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.