json - 如何使用 Spring Boot 在 Mongo 中存储原始 JSON

标签 json mongodb spring-boot

我想使用 JSON 获取 HTTP PUT 请求并将其未经修改地存储在 Mongo 中。我怎样才能做到这一点?我拥有的最好的就是这个:

@RestController
public class ConfigurationController {

    @Autowired
    private MongoTemplate mongoTemplate;

    @RequestMapping
    public DBObject index() {
        return mongoTemplate.getCollection("foo").findOne();
    }

    @RequestMapping(method = RequestMethod.PUT)
    ResponseEntity<?> add(@RequestBody DBObject object) {

        mongoTemplate.insert(object, "foo");

        return new ResponseEntity<>(null, HttpStatus.CREATED);
    }

}

最佳答案

在较新版本的 Mongodb (mongo-java-driver 3.0+) 中,API 使用 org.bson.Document,因此您的解决方案应如下所示:

@RestController
public class ConfigurationController {

   @Autowired
   private MongoTemplate mongoTemplate;

   @RequestMapping(method = RequestMethod.PUT)
   ResponseEntity<?> add(@RequestBody String jsonString) {

       Document doc = Document.parse(jsonString)
       mongoTemplate.insert(doc, "foo");

       return new ResponseEntity<>(null, HttpStatus.CREATED);
   }

}

关于json - 如何使用 Spring Boot 在 Mongo 中存储原始 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29656128/

相关文章:

json - 如何为每个字段选择 Excel 表中给出的 JSON 节点?

json - Powershell JSON管道将多个值扩展为一列csv

java - org.springframework.beans.factory.UnsatisfiedDependencyException ,没有类型 [edu.sample.service.ItemService] 的合格 bean

java - 如何使 feign disable-ssl-validation 属性在 Spring Boot 上工作

spring - 如何在Spring Boot应用中为@Configuration注解的类编写单元测试用例

json - 在 OutbreakLocation 上运行 evalMetrics API 时出错

json - 在 Flutter 的 Ferry Graphql 中序列化标量 JSON 以实现灵活的查询

尽管类型正确,json 模式验证仍失败

mongodb - Mongo删除和插入与更新

java - 这是在同一 Mongodb 查询中查找最小值和最大值的最佳方法