搭建框架 下载安装 MongoDB https://www.mongodb.com/download-center 添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> 新建实体 @Data public class User{ //MongoDB自动生成主键 @ID private String userId; private String username; private String password; } 新建接口 @Repository public class UserRepository { @Autowired private MongoTemplate mongoTemplate; /** * 保存 * @param user User对象 */ public void save(User user) { mongoTemplate.save(user); } /** * 根据id查找 * @param userId 主键id * @return user 对象 */ public User getUserById(String userId) { Query query = new Query(Criteria.where("userId").in(userId)); User user = mongoTemplate.findOne(query, User.class); return user; } /** * 更新 * @param user 对象 * @return 结果集的第一条 */ public long update(User user) { Query query = new Query(Criteria.where("id").is(user.getUserId())); Update update = new Update().set("username", user.getUsername()).set("password", user.getPassword()); //更新查询返回结果集的第一条 UpdateResult result = mongoTemplate.updateFirst(query, update, User.class); if (result != null) { return result.getMatchedCount(); } else { return 0; } } /** * 查询对象 * @param userId 主键id */ public void remove(String userId) { Query query = new Query(Criteria.where("userId").in(userId)); mongoTemplate.remove(query, User.class); } } 测试 @Slf4j public class UserRepositoryTest extends VillageDoctorApplicationTests { @Autowired private UserRepository userRepository; @Test public void save() { User user=new User(); user.setUserId(123L); user.setUsername("stop"); user.setPassword("abcd"); userRepository.save(user); } @Test public void getUserById() { User user = userRepository.getUserById("123"); log.info("查询结果:{}",user); } @Test public void remove() { userRepository.remove("123"); } @Test public void update() { User user=new User(); user.setUserId(123L); user.setUsername("start"); user.setPassword("abcde"); userRepository.update(user); } }