0

I am new to mongodb.So in sql to update the specific fields the query is

In sql::

update students set marks = 95, grade = 'A' where _id = '1234';

In mongo shell ::

db.students.update({_id:'1234'},{"$set":{"marks":95,"grade":'A'}},{multi:false});

Using mongotemplate , how can we acheive this. I have tried using the following code for single field update and it is working.

String uniqueId = student.getSection() + "#" + student.getRollNo();
    Query query = new Query();
    query.addCriteria(Criteria.where("_id").is(uniqueId));
    Update update = Update.update("marks", student.getMarks());
    logger.info("[Updating the Student marks using the id=]["+uniqueId+"]");
    UpdateResult result =  mongoTemplate.updateFirst(query, update, Student.class);

But how we acheive to update grade also using mongo templete?
Note :: I want to update specific fields in the document , not replacing the entire document

1 Answer 1

1

Call .set(key, value)

Update update = Update.update("marks", student.getMarks()).set("grade", student.getGrade());

//Alternative
Update update = new Update().set("marks", student.getMarks()).set("grade", student.getGrade());
Sign up to request clarification or add additional context in comments.

2 Comments

Hi @Valijon, thanks for the answer. It is working. But if i want to update the multiple fields without disturbing the existing fields, how can i acheive through pojo object ?. Is there any function like( saveorUPDATE like present in hibernate) ?
@user11790395 Give an example please

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.