Home > Blockchain >  Update Specific fields in a document record using MONGODB
Update Specific fields in a document record using MONGODB

Time:12-20

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

CodePudding user response:

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());
  • Related