简体   繁体   English

使用 MONGODB 更新文档记录中的特定字段

[英]Update Specific fields in a document record using MONGODB

I am new to mongodb.So in sql to update the specific fields the query is我是 mongodb 的新手。所以在 sql 中更新查询的特定字段

In sql::在 sql::

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

In mongo shell::在蒙戈 shell::

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

Using mongotemplate, how can we acheive this.使用 mongotemplate,我们如何实现这一点。 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?但是我们如何使用 mongo Templete 来更新成绩呢?
Note :: I want to update specific fields in the document, not replacing the entire document注意:: 我想更新文档中的特定字段,而不是替换整个文档

Call .set(key, value)调用.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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM