MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。MongoDB 将数据存储为一个文档,数据结构由键值对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组。
在 Spring 中,spring-data-mongodb 项目对访问 MongoDB 进行了 API 封装,提供了便捷的访问方式。 Spring Data MongoDB 的核心是一个以 POJO 为中心的模型,用于与 MongoDB DBCollection 交互并轻松编写 Repository 样式的数据访问层。
// save a couple of customers repository.save(newCustomer("Alice", "Smith")); repository.save(newCustomer("Bob", "Smith"));
// fetch all customers System.out.println("Customers found with findAll():"); System.out.println("-------------------------------"); for (Customer customer : repository.findAll()) { System.out.println(customer); } System.out.println();
// fetch an individual customer System.out.println("Customer found with findByFirstName('Alice'):"); System.out.println("--------------------------------"); System.out.println(repository.findByFirstName("Alice"));
System.out.println("Customers found with findByLastName('Smith'):"); System.out.println("--------------------------------"); for (Customer customer : repository.findByLastName("Smith")) { System.out.println(customer); } }
}
运行 DataMongodbApplication 的 main 方法后,输出类似如下类容:
1 2 3 4 5 6 7 8 9 10 11 12
Customers found with findAll(): ------------------------------- Customer(id=63d6157b265e7c5e48077f63, firstName=Alice, lastName=Smith) Customer(id=63d6157b265e7c5e48077f64, firstName=Bob, lastName=Smith) Customer found with findByFirstName('Alice'): -------------------------------- Customer(id=63d6157b265e7c5e48077f63, firstName=Alice, lastName=Smith) Customers found with findByLastName('Smith'): -------------------------------- Customer(id=63d6157b265e7c5e48077f63, firstName=Alice, lastName=Smith) Customer(id=63d6157b265e7c5e48077f64, firstName=Bob, lastName=Smith)