数据库
首页 > 数据库> > mongodb-java常用语法-增删改查

mongodb-java常用语法-增删改查

作者:互联网

1. 查找

@Autowired
MongoTemplate mongoTemplate;
// 具体语句
Query query = new Query(); // 添加查询条件 方法1 query.addCriteria(Criteria.where("funcName").is(funcName)); query.addCriteria(Criteria.where("userId").is(userId));
// 或者 方法2

query.addCriteria(Criteria.where("funcName").is(funcName) and("userId").is(userId));
// 倒排序 query = query.with(Sort.by(Sort.Order.desc("createTime"))); // 总数 long totalCount = mongoTemplate.count(query, Student.class); // 分页查询 query = query.limit(limit).skip((page - 1) * limit); List<Student> student = mongoTemplate.find(query, Student.class);

2. 插入

RecordModel recordModel = new RecordModel(null,"查询记录" ,"",new Date(new Timestamp(System.currentTimeMillis()).getTime()),"普通操作");
mongoTemplate.insert(recordModel);

3. 删除

 deleteRecord(id, StudentMhd.class);

 public  ResponseMessage deleteRecord(String id, Class<?> entityClass){
        log.info("deleteRecord:id={}", id);
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(new ObjectId(id)));
        DeleteResult result = mongoTemplate.remove(query, entityClass);
        if(result != null){
            return ResponseMessage.successMessage("恭喜,删除记录成功~");
        }
        return ResponseMessage.failedMessage("删除记录失败");
    }

4. 更新

@Autowired
    MongoTemplate mongoTemplate;
    public ResponseMessage updateRecord(Student student) {
        if(studentMhd == null){
            return ResponseMessage.failedMessage("参数错误,请重新检查参数!");
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(new ObjectId(student.getId())));
        studentMhd.setCreateTime(new Date(new Timestamp(System.currentTimeMillis()).getTime()));
        Document doc = new Document();
        mongoTemplate.getConverter().write(studentMhd, doc);
        Update update = Update.fromDocument(doc);
        UpdateResult result = mongoTemplate.upsert(query, update, "student_table");
        if(result != null){
            return ResponseMessage.successMessage("恭喜,更新记录成功~","登录用户名:" +student.getLoginId() +", 用户:"+ student.getUserId()+ ", courseId:" + student.getCourseId());
        }
        return ResponseMessage.failedMessage("更新记录失败", "登录用户名:" +student.getLoginId() +", 用户:"+ student.getUserId()+ ", courseId:" + student.getCourseId());
    }

  

 

标签:java,mongodb,改查,mongoTemplate,ResponseMessage,student,query,new,id
来源: https://www.cnblogs.com/leavescy/p/14621730.html