1

I have documents like below in a collection named event in mongoDB

{
    "name": "pick",
    "message": {
        "word": "seven",
        "sequenceNumber": 34
    }
}

which existed before I developed my Spring Boot application to access it. Now I have a java object Event.java to access the above collection.

public class Event{
    private String name;
    private JSONObject messgae;
    // getters setters costructors
}

In the document, the message could be any json. So defining a class for message does not make any sense. I have tried using mongoOperations, mongoTemplate and mongoRepository but I am not able to access the the document and change the value and store it again. The problems I face are,

  1. I could not use JSONObject for message because mongoOperations has no support
  2. I could not use String for message because when I save the object again it gets serialized like "message":"{\"word ...

Is there any way I can access, modify and store the data via spring boot application?

1 Answer 1

1

You can use JSONObject for message in mongoOperations like below.

JSONObject jsonObj= new JSONObject();
jsonObj.put("word", "seven");
jsonObj.put("sequenceNumber", new Integer(34));

//save
Event eventDocument = new Event("pick",jsonObj);
mongoOperations.save(eventDocument);

//find
Query query = new Query(Criteria.where("name").is("pick"));
Event object = (Event) mongoOperations.findOne(query, Event.class);
System.out.println(object.getName());
System.out.println(object.getMessage());
Sign up to request clarification or add additional context in comments.

3 Comments

What's the full class name? is JSONObject from an external library?
Thanks, I did using json-simple, it worked like a charm

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.