【问题标题】:mongodb morphia save with id not override带有id的mongodb morphia保存不覆盖
【发布时间】:2017-08-23 16:27:23
【问题描述】:

mongo morphia basicDAO.save() 基本可以

save(T entity)
Saves the entity; either inserting or overriding the existing document

如果 entity.id 不为空,morphia 将尝试覆盖现有文档,有没有办法让 morphia 抛出重复键异常(就像 mongodb 一样)?

【问题讨论】:

  • 只是好奇 - 你的 @Id 字段是什么?为什么不使用 ObjectId,你几乎可以保证没有冲突

标签: mongodb morphia


【解决方案1】:

您最好的方法是检查文档是否已经存在。性能最高的是使用:

db.collection.find({_id: “myId”}, {_id: 1}).limit(1)

然后检查是否为空。 'findOne' 实际上会从数据库中加载文档,所以要避免这种情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-06
    • 2018-08-22
    • 2019-02-28
    • 2018-09-24
    相关资源
    最近更新 更多