2

Consider the following Java Class.

class Transaction {
@Id
public String id;
public String firstProperty;
public String secondProperty;
} 

In Java following code is executed : (mongoTemplate is of type Mongoperations)

Transaction transaction = new Transaction("T1");
transaction.setFirstProperty("first");
Query query = Query.query(Criteria.where("_id").is("T1"));
DBObject dbObject = new BasicDBObject();
mongoTemplate.getConverter().write(transactionInfo, dbObject);
Update update = Update.fromDBObject(dbObject);
mongoTemplate.upsert(query , update , TransactionInfo.class);

Following document is created.

{
_id:123,
firstProperty: "first"
}

If this piece of code is executed later :

Transaction transaction = new Transaction("T1");
transaction.setSecondProperty("second");
Query query = Query.query(Criteria.where("_id").is("T1"));
mongoTemplate.upsert(query , update , TransactionInfo.class);

Expected Document :

{
_id:123,
firstProperty: "first",
secondProperty: "second"
}

Actual Document:

{
_id:123,
secondProperty: "second"
}

From what I read in MongoDB docs I expect the document to be updated with "secondProperty" but it results in the removal of "firstProperty" . I think the document is getting created again, instead of getting updated. Please let me know if I am missing something.

0 Answers0