Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a store raw JSON in Mongo using Spring Boot

I'd like to take HTTP PUT request with JSON and store it unmodified in Mongo. How can I do this? The best I have is this:

@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);
    }

}
like image 792
user2732949 Avatar asked Apr 15 '15 16:04

user2732949


People also ask

Can we store JSON in MongoDB?

Does MongoDB use BSON or JSON? MongoDB stores data in BSON format both internally, and over the network, but that doesn't mean you can't think of MongoDB as a JSON database. Anything you can represent in JSON can be natively stored in MongoDB, and retrieved just as easily in JSON.

How do I import a JSON file into MongoDB?

Open the Import Wizard. Then, choose JSON as the import format and click OK. Click on + to add JSON source documents, – to remove them, or the clipboard icon to paste JSON data from the clipboard.

Where should I put JSON in spring boot?

json and place it inside of /src/main/resources/json/. Each JSON record for a user will look something like this.

Can we use spring boot with MongoDB?

It's Easy to Connect MongoDB Atlas with Spring Boot Through this article, we demonstrated that MongoDB Spring Boot integration is easy using: Starter data MongoDB artifactid (the dependency we added while creating the Spring Initializr project) in pom. xml. A property on application.


1 Answers

In newer versions of Mongodb (mongo-java-driver 3.0+) the API uses org.bson.Document, so your solution should look like this:

@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);
   }

}
like image 124
Rodrigo Villalba Zayas Avatar answered Sep 17 '22 11:09

Rodrigo Villalba Zayas