【问题标题】:Save dots '.' in key as a field in MongoDB using SpringBoot保存点“。”使用 Spring Boot 将键作为 MongoDB 中的字段
【发布时间】:2019-10-09 18:21:01
【问题描述】:

我有 json 数据,其中键包含点作为“123.456”,值作为对象。

  {
        "models": {
            "123.456": [{
                "key1": "value1",
                "key2": "value2"
            }]
        }
    }

尝试在 MongoDB 中保存对象时出现映射异常,如下所示

org.springframework.data.mapping.model.MappingException: Map key 123.456 contains dots but no replacement was configured!Make sure map keys don't contain dots in the first place or configure an appropriate replacement!

Spring Mongo 中是否支持将键保存为包含点的字段?

【问题讨论】:

    标签: spring mongodb spring-boot spring-mongodb


    【解决方案1】:

    你必须使用MappingMongoConverter 类。它有setMapKeyDotReplacement(String mapKeyDotReplacement) 方法。

    根据Spring-MongoDB Docs

    setMapKeyDotReplacement(String mapKeyDotReplacement)方法检查点是否存在于地图中。如果找到,则应将其替换为指定的字符。

    使用示例:

    @Component
    public class Example {
    
        @Autowired
        private MappingMongoConverter mappingMongoConverter;
    
        public void replaceKeyContainingDot() {
          mappingMongoConverter.setMapKeyDotReplacement("pass here the character you want to replace the dots with");
        }
    
    } 
    

    注意:来自MongoDB Docs

    $ 和 .不建议在字段名称中,也不是 由官方 MongoDB 驱动程序支持。

    我从文档中找到了一种解决方法。您可能必须覆盖 MappingMongoCoverter 类中的 potentiallyEscapeMapKey(String source)potentiallyUnescapeMapKey(String source) 方法。

    请参阅此处的热门 SO 问题以获取更多信息和更好的理解:

    1. How to customize MappingMongoConverter (setMapKeyDotReplacement) in Spring-Boot without breaking the auto-configuration?

    2. MongoDB-Escape dots '.' in map key

    【讨论】:

    • 但我不想替换点,而是想按原样保存点,当我使用 mongoMappingConverter.setMapKeyDotReplacement(".") 时,我收到 Invalid bson field dot exception。跨度>
    • 来自 mongo db 文档,$ 和 .不推荐使用 in 字段名称,并且官方 MongoDB 驱动程序不支持。
    • Mongo 3.6 允许在字段名称中使用点和美元符号docs.mongodb.com/manual/core/document
    • @shashank 那么,您使用的是 MongoDB 3.6 吗?
    • 是的,我正在阅读文档并考虑尝试使用此方法可能 EscapeMapKey(".")
    猜你喜欢
    • 2019-03-16
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 2013-11-28
    • 2019-10-30
    • 2019-04-16
    相关资源
    最近更新 更多