【问题标题】:how to create dynamic attributes for different data types and store in mongodb如何为不同的数据类型创建动态属性并存储在mongodb中
【发布时间】:2019-12-02 05:34:14
【问题描述】:

我在使用 Java 创建具有不同数据类型(intbooleanfloatdoublelongStringbyte,...)的动态属性时遇到问题使用 Spring Boot REST API 并存储在 MongoDB 集合中。我该如何解决这个问题?

@Field(value = "attributes")
Map<String, Object> attributes = new LinkedHashMap<>();

/*
 * setter for map attributes
 */
@JsonAnySetter
public void setAttributes(String key, Object value) {

    Set<Map.Entry<String, Object>> s = attributes.entrySet();

    for (Map.Entry<String, Object> it : s) {
        key = it.getKey();
        value = it.getValue();
        this.attributes.put(key, value);
    }
}

我正在使用这个,但它只将所有数据类型存储为String。 我不需要存储任何值,只需要存储特定数据类型的属性。

【问题讨论】:

    标签: java arrays mongodb spring-boot mongodb-query


    【解决方案1】:

    我不明白为什么您的解决方案不起作用。尝试下一个:

    用你的属性指定一些类:

    import java.util.Map;
    import org.springframework.data.mongodb.core.mapping.Document;
    
    @Document
    public class User {
    private Map<String, Object> attributes;
    
    public User(Map<String, Object> attributes) {
        this.attributes = attributes;
    }
    
    public Object getAttribute() {
        return this.attributes;
    }}
    

    指定 mongodb 存储库:

    interface UserRepository extends MongoRepository<User, UUID> {}
    

    控制器保存虚拟用户:

    @RestController
    public class DemoController {
    
    @Autowired
    UserRepository userRepository;
    
    @GetMapping("/save")
    public User doSave() {
        Map<String, Object> attributes = new HashMap<>();
    
        attributes.put("time", Instant.now());
        attributes.put("num", 5.6);
        attributes.put("str", "5.6");
    
        return userRepository.save(new User(attributes));
    }
    }
    

    我收到了下一个回复:

    {
    "attribute": {
        "str": "5.6",
        "num": 5.6,
        "time": "2019-07-24T12:22:07.390Z"
    }
    }
    

    MongoDB 中的对象:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-31
      • 2020-04-30
      • 1970-01-01
      相关资源
      最近更新 更多