【问题标题】:Update Specific fields in a document record using MONGODB使用 MONGODB 更新文档记录中的特定字段
【发布时间】:2022-01-20 22:32:08
【问题描述】:

我是 mongodb 的新手。所以在 sql 中更新查询的特定字段

在 sql::

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

在 mongo shell ::

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

使用 mongotemplate ,我们如何实现这一点。我尝试使用以下代码进行单字段更新,并且它正在工作。

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);

但是我们如何使用 mongo Templete 来更新成绩?
注意 :: 我想更新文档中的特定字段,而不是替换整个文档

【问题讨论】:

    标签: java mongodb spring-boot mongodb-query


    【解决方案1】:

    致电.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());
    

    【讨论】:

    • 嗨@Valijon,感谢您的回答。这是工作。但是,如果我想在不干扰现有字段的情况下更新多个字段,我该如何通过 pojo 对象来实现?有没有类似的功能(saveorUPDATE 像休眠中存在的那样)?
    • @user11790395 请举个例子
    猜你喜欢
    • 1970-01-01
    • 2013-01-06
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-04-13
    • 2018-05-11
    • 1970-01-01
    相关资源
    最近更新 更多