g0c00l.g33k
g0c00l.g33k

Reputation: 2618

MongoDB Java Async Driver replaceOne doesn't seem to work

I am trying to update a document with MongoDB Async Java Driver and my code is below,

// jsonString is a string of "{_id=5715e426ed3522391f106e68, name=Alex}
final Document document = Document.parse(jsonString);

Document newDocument = document.append("status", "processing");
mongoDbCollection.replaceOne(document, newDocument, (updateResult, throwable) -> {
              if (updateResult != null) {
                 log.info("UPDATED DOC ::::::>>> " + newDocument.toJson());
                 log.info("UPDATED RESULT ::::>> "+updateResult.toString());
              } else {
                 throwable.printStackTrace();
                 log.error(throwable.getMessage());
              }
   });

As per the logging, I do see the updated document as below,

INFO: UPDATED DOC ::::::>>> { "_id" : { "$oid" : "5715e426ed3522391f106e68" }, "status":"processing"}
INFO: UPDATED RESULT ::::>> AcknowledgedUpdateResult{matchedCount=0, modifiedCount=0, upsertedId=null}

But when I see the collection via Robmongo I do not see the updated document and it still shows the old document. I have double checked I am looking in the same collection and there aren't any exceptions. Am I doing something wrong here?

Upvotes: 1

Views: 511

Answers (1)

Blakes Seven
Blakes Seven

Reputation: 50416

The problem here is this line:

Document newDocument = document.append("status", "processing");

Where you "thought" you were just assigning a "new document copy", but actually this "also" modifies the document object to append the field.

As such, the query does not match, just as indicated in your output:

{matchedCount=0, modifiedCount=0, upsertedId=null}
           // ^ Right here! See 0 matched

So what you want is a "clone". It's not straightforward with a Document, but can be done with this slightly "hacky" method:

Document document = Document.parse(jsonString);

Document newDocument = Document.parse(document.toJson()).append("status","processing");

System.out.println(newDocument);
System.out.println(document);

Now you will see that newDocument contains the addition, whilst document remains unaltered, which is not the case with your current code, and why the query does not match anything to update.

Upvotes: 1

Related Questions