• JAVA操作MongoDB实例详解
  • 发布于 2个月前
  • 250 热度
    0 评论
三分钟的时间,通过本文你将学会
1.MongoDB主要特征
2.MongoDB优缺点,扬长避短
3.何时选择MongoDB?为啥要用它?
4.MongoDB与MySQL关键字对比
5.下载与安装MongoDB
6.Java整合MongoDB,实现增删改查

MongoDB和MySQL的区别
数据模型不同:MySQL是关系型数据库,而MongoDB是文档型数据库。MongoDB的数据模型更加灵活,可以存储非结构化数据,适合处理大量的半结构化数据。
处理大数据量:MongoDB可以处理海量数据,而MySQL在处理大数据量时可能会出现性能瓶颈。MongoDB的分布式架构可以轻松地扩展到多个节点,以处理大量数据。
高可用性:MongoDB具有高可用性和容错性,可以在多个节点之间自动分配数据,确保数据的可靠性和可用性。
适合云计算:MongoDB是云计算时代的理想选择,可以轻松地在云端部署和管理,而MySQL则需要更多的配置和管理。
适合实时应用:MongoDB支持实时数据处理和实时查询,适合于需要快速响应的实时应用场景。

MongoDB主要特征
面向文档的数据模型:MongoDB是一种文档型数据库,数据以文档的形式存储,每个文档可以包含不同的字段和值,这种数据模型比传统的关系型数据库更加灵活。

高性能:MongoDB具有高性能的读写能力,支持高并发和快速的数据查询。
分布式架构:MongoDB支持分布式架构,可以轻松地扩展到多个节点,以处理大量数据。
高可用性:MongoDB具有高可用性和容错性,可以在多个节点之间自动分配数据,确保数据的可靠性和可用性。
索引支持:MongoDB支持多种类型的索引,包括单字段索引、复合索引、全文索引等,可以提高数据查询的效率。
强大的查询语言:MongoDB支持强大的查询语言,包括聚合管道、地理空间查询、文本搜索等,可以满足不同的查询需求。
可扩展性:MongoDB可以轻松地扩展到多个节点,以处理大量数据和高并发请求。

MongoDB优缺点,扬长避短
MongoDB的优点:
灵活的数据模型:MongoDB的文档型数据模型非常灵活,可以存储半结构化数据,适合处理不同类型的数据。
高性能:MongoDB具有高性能的读写能力,支持高并发和快速的数据查询。
分布式架构:MongoDB支持分布式架构,可以轻松地扩展到多个节点,以处理大量数据。
高可用性:MongoDB具有高可用性和容错性,可以在多个节点之间自动分,确保数据的可靠性和可用性。
索引支持:MongoDB支持多种类型的索引,包括单字段索引、复合索引、全文索引等,可以提高数据查询的效率。
强大的查询语言:MongoDB支持强大的查询语言,包括聚合管道、地理空间查询、文本搜索等,可以满足不同的查询需求。

可扩展性:MongoDB可以轻松地扩展到多个节点,以处理大量数据和高并发请求。


MongoDB的缺点:

不支持事务:MongoDB在早期版本中不支持事务,虽然在最新版本中已经支持了事务,但是相比传统的关系型数据库还是有所不足。
内存占用较高:MongoDB在处理大量数据时,需要占用较多的内存,如果内存不足,可能会导致性能下降。
数据库设计需要谨慎:MongoDB的灵活性也带来了一定的挑战,需要谨慎设计数据库结构,避免出现数据冗余和不一致的情况。
存储空间占用较大:MongoDB在存储数据时,需要占用较大的存储空间,如果数据量较大,可能会导致存储成本较高。
综上所述,MongoDB具有灵活的数据模型、高性能、分布式架构、高可用性、索引支持、强大的查询语言、可扩展性和开源等优点,但是不支持事务、内存占用较高、数据库设计需要谨慎、存储空间占用较大等缺点需要注意。

何时选择MongoDB?为啥要用它?
(1)游戏场景
使用MongoDB存储游戏用户信息、装备、积分等,直接以内嵌文档的形式存储,方便查询、更新。

(2)物流场景
使用MongoDB存储订单信息、订单状态、物流信息,订单状态在运送过程中飞速迭代、以MongoDB内嵌数组的形式来存储,一次查询就能将订单所有的变更查出来,牛逼plus。

(3)社交场景
使用MongoDB存储用户信息,朋友圈信息,通过地理位置索引实现附近的人、定位功能。

(4)物联网场景
使用MongoDB存储设备信息、设备汇报的日志信息、并对这些信息进行多维度分析。

(5)视频直播
使用MongoDB存储用户信息、点赞互动信息。

MongoDB与MySQL关键字对比

下载与安装
以下是MongoDB的下载和安装步骤:
1.访问MongoDB官网(https://www.mongodb.com/),点击“Download”按钮。
2.在“Community Server”下选择适合自己操作系统的版本,如Windows、macOS或Linux等。
3.下载完成后,双击安装程序,按照提示进行安装。
4.安装完成后,打开命令行工具,输入“mongo”命令,如果出现“MongoDB shell version x.x.x”等信息,则表示安装成功。
5.如果需要在本地创建数据库,可以在命令行工具中输入“mongod”命令,启动MongoDB服务。
6.在浏览器中输入“http://localhost:27017/”,可以访问MongoDB的Web管理界面。

注意事项:
1.安装过程中需要选择安装路径和数据存储路径,建议选择默认路径。
2.安装完成后需要将MongoDB的bin目录添加到系统环境变量中,以便在命令行中使用MongoDB命令。
3.在启动MongoDB服务前,需要先创建数据存储目录,可以在命令行中输入“mkdir data\db”命令创建。
4.在使用MongoDB时,需要先连接到MongoDB服务,可以在命令行中输入“mongo”命令连接到本地MongoDB服务。

Java整合MongoDB,实现增删改查
1.整合Spring Boot和MongoDB,实现学生的增删改查的步骤如下:
创建Spring Boot项目,并添加MongoDB的依赖。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
然后配置连接信息:

在application.properties或application.yml文件中添加MongoDB的连接信息,例如:
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=mydb
其中,host和port分别是MongoDB的主机名和端口号,database是要连接的数据库名称。如果MongoDB需要进行身份验证,还需要添加以下配置:
spring.data.mongodb.username=myuser
spring.data.mongodb.password=mypassword
其中,username和password分别是MongoDB的用户名和密码。

2.创建学生实体类。
@Document(collection = "student")
public class Student {
    @Id
    private String id;
    private String name;
    private int age;
    // 省略getter和setter方法
}
3.创建学生Repository接口。
@Repository
public interface StudentRepository extends MongoRepository<Student, String> {
}
4.创建学生Service接口和实现类。
public interface StudentService {
    List<Student> findAll();
    Student findById(String id);
    void save(Student student);
    void deleteById(String id);
}
 // 堆代码 duidaima.com
@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentRepository studentRepository;

    @Override
    public List<Student> findAll() {
        return studentRepository.findAll();
    }

    @Override
    public Student findById(String id) {
        return studentRepository.findById(id).orElse(null);
    }

    @Override
    public void save(Student student) {
        studentRepository.save(student);
    }

    @Override
    public void deleteById(String id) {
        studentRepository.deleteById(id);
    }
}
5.创建学生Controller类。
@RestController
@RequestMapping("/students")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @GetMapping("")
    public List<Student> findAll() {
        return studentService.findAll();
    }

    @GetMapping("/{id}")
    public Student findById(@PathVariable String id) {
        return studentService.findById(id);
    }

    @PostMapping("")
    public void save(@RequestBody Student student) {
        studentService.save(student);
    }

    @PutMapping("/{id}")
    public void update(@PathVariable String id, @RequestBody Student student) {
        student.setId(id);
        studentService.save(student);
    }

    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable String id) {
        studentService.deleteById(id);
    }
}
完整代码示例:
Student.java
@Document(collection = "student")
public class Student {
    @Id
    private String id;
    private String name;
    private int age;
    // 省略getter和setter方法
}
StudentRepository.java
@Repository
public interface StudentRepository extends MongoRepository<Student, String> {
}
StudentService.java
public interface StudentService {
    List<Student> findAll();
    Student findById(String id);
    void save(Student student);
    void deleteById(String id);
}

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentRepository studentRepository;

    @Override
    public List<Student> findAll() {
        return studentRepository.findAll();
    }

    @Override
    public Student findById(String id) {
        return studentRepository.findById(id).orElse(null);
    }

    @Override
    public void save(Student student) {
        studentRepository.save(student);
    }

    @Override
    public void deleteById(String id) {
        studentRepository.deleteById(id);
    }
}
StudentController.java
@RestController
@RequestMapping("/students")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @GetMapping("")
    public List<Student> findAll() {
        return studentService.findAll();
    }

    @GetMapping("/{id}")
    public Student findById(@PathVariable String id) {
        return studentService.findById(id);
    }

    @PostMapping("")
    public void save(@RequestBody Student student) {
        studentService.save(student);
    }

    @PutMapping("/{id}")
    public void update(@PathVariable String id, @RequestBody Student student) {
        student.setId(id);
        studentService.save(student);
    }

    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable String id) {
        studentService.deleteById(id);
    }
}

总结
MongoDB是一种基于文档的NoSQL数据库,具有高性能、高可用性、可扩展性等优点。它使用BSON格式存储数据,支持复杂的查询和聚合操作,同时还提供了分布式锁、事务等功能。MongoDB的数据模型非常灵活,可以根据应用程序的需要进行自由设计。在Spring Boot中,可以通过引入MongoDB的依赖和配置连接信息来使用MongoDB,同时使用Spring Data MongoDB来操作MongoDB数据库。
用户评论