【问题标题】:mongoDB ignoring unique indexmongoDB忽略唯一索引
【发布时间】:2019-05-22 03:46:18
【问题描述】:

我构建了一个 REST 服务,我发现使用 Gson 从 ObjectId 生成的 JSON 字符串的格式与 spring-boot 生成的格式不同。如果我将 GSON 格式的现有文档的 _id 字段的 ObjectId 发送到我的 REST 服务并使用 mongorepository 的保存功能将其保存到集合中,即使在此类上设置了唯一索引,仍将插入具有重复 _id 的新文档场地。但是,如果我以 spring-boot 生成的格式发送 ObjectId,一切都会完美运行。我想知道是什么导致了这样的问题?

        "timestamp": 1558461711,
        "machineIdentifier": 5077764,
        "processIdentifier": 21816,
        "counter": 13546695,
        "date": "2019-05-21T18:01:51.000+0000",
        "time": 1558461711000,
        "timeSecond": 1558461711(generated by spring-boot)


        "counter": 13546695,
        "randomValue1": 9256029,
        "randomValue2": 856,
        "timestamp": 1558461711(by GSON)

【问题讨论】:

    标签: mongodb spring-boot mongorepository


    【解决方案1】:

    如果您正在使用 mongodb,最好使用 org.bson.Document(由 mongodb 依赖项提供)或其他一些 mongodb 类将文档转换为 json 而不是 GSON。

    Document document = new Document();
    document.put("_id", new ObjectId());
    String json = document.toJson()
    

    document.toJson() 应该以正确的方式对 ObjectId 进行字符串化。 实际上上面代码的输出是:

    { "_id" : { "$oid" : "5ce51fb47dda11a8507087eb" } }
    

    这是 mongodb 的有效格式,不确定 SpringBoot 会如何反应。
    无论如何,希望它会有所帮助。

    【讨论】:

    • 嗯...不知道为什么,但似乎 SpringBoot 无法从该字符串化值中获取正确的 ObjectId。
    猜你喜欢
    • 2016-06-15
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    相关资源
    最近更新 更多