• 请不要在回答技术问题时复制粘贴 AI 生成的内容
SlipStupig
V2EX  ›  程序员

mongodb update 建立了唯一索引还是能被更新

  •  
  •   SlipStupig · May 17, 2017 · 3067 views
    This topic created in 3354 days ago, the information mentioned may be changed or developed.
    数据结构:
    {"user": 1, "pwd": "1234"}
    我想更新 pwd 字段但是 pwd 字段不能和上一次相同, 于是我建立了唯一索引给 pwd 但是同样的还是可以更新一模一样的数据, 有什么好的解决办法不写入新的字段又能更新
    3 replies    2017-05-17 19:15:39 +08:00
    windfarer
        1
    windfarer  
       May 17, 2017   ❤️ 1
    唯一索引的意思是你不能再插入那个字段相同的条目了,而不是不能更新原有的条目
    hl
        2
    hl  
       May 17, 2017   ❤️ 4
    官方解释唯一索引的含义是这样的:
    Unique Index
    A unique index ensures that the indexed fields do not store duplicate values; i.e. enforces uniqueness for the indexed fields. By default, MongoDB creates a unique index on the _id field during the creation of a collection.

    你的做法带来的效果是:
    你对 pwd 字段做唯一索引,起到的作用是你插入的所有的记录中的 pwd 字段不能有重复

    你的需求:
    我默认你的 update 操作不是在通过命令行进行的试验,而是一个业务需求,这不是一个数据库级别的方案。
    或许你在以前的关系型数据库比如 oracle,mysql,可能通过触发器之类的能实现的了。
    但 mongodb 是个文档 nosql 数据库,是个 kv 的松散结构,你想要做到 pwd 字段 update 新的值进去不能和以前的值是一样的,这纯属“唯一索引”概念不清楚。

    你需要的方案是:
    通过书写一段逻辑代码,在 update pwd 字段时,对比库里的值和接收过来的值是否相同,不相同则进行更新,相同则返回给调用方 pwd 值不能与以前的一样。
    SlipStupig
        3
    SlipStupig  
    OP
       May 17, 2017
    @hl
    @windfarer
    感谢二位耐心解答
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2932 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 14:52 · PVG 22:52 · LAX 07:52 · JFK 10:52
    ♥ Do have faith in what you're doing.