Search code examples
updatingmongodb-java

updating mongodb using java 3.2


I am trying to update my document based on pattern matcher in mongodb using java 3.2. So far I tried to retrieve all the fields using for loop and matched with pattern matcher, after that the status field should get updated. But, I got an error "Exception in thread "main" com.mongodb.util.JSONParseException:". Is there any other way to achieve this?

Here is my sample.

FindIterable alldoc = db.getCollection("sortedTweets").find(new Document("lang","en"));

for(Document doc:alldoc){

    String screenName = doc.get("screen_name").toString();
    String stat = doc.get("status").toString();

    Matcher r = p1.matcher(stat);
    if(r.find()){
        stat = r.replaceAll(replace);

        Document status =  (Document) JSON.parse(stat);
        Document screenname =  (Document) JSON.parse(screenName);
        db.getCollection("unsortedTweets").updateOne(screenname, status);
    }

Solution

  • regarding the below 2 lines of code

    Document status =  (Document) JSON.parse(stat);
    Document screenname =  (Document) JSON.parse(screenName);
    

    i assume you are tying to make a document of the string stat. For JSON.parse() to work your stat and screenName should be proper JSON documents.

    Print them out first and see where the invalid JSON element is in them. the invalid part will also be pointed out in the rest of the exception log displayed