范文健康探索娱乐情感热点
投稿投诉
热点动态
科技财经
情感日志
励志美文
娱乐时尚
游戏搞笑
探索旅游
历史星座
健康养生
美丽育儿
范文作文
教案论文

SpringBoot整合MongoDB超详细

  一、介绍
  在前面的文章中,我们详细的介绍了 MongoDB 的配置和使用,如果你对 MongoDB 还不是很了解,也没关系,在 MongoDB 中有三个比较重要的名词: 数据库、集合、文档 ! 数据库(Database) :和关系型数据库一样,每个数据库中有自己的用户权限,不同的项目组可以使用不同的数据库集合(Collection) :集合指的是文档组(类似于 Mysql 中的表的概念),里面可以存储许多文档文档(Document) :文档是 MongoDB 中最基本的数据单元,由键值对组成,类似于 JSON 格式,可以存储不同字段,字段的值可以包括其他文档、数组和文档数组
  搞懂这三个名词,基本就可以上手了,今天我们以 Java 语言为例,详细的介绍 Java 客户端改如何操作 MongoDB !
  话不多说,直接开撸! 二、Java 客户端2.1、MongoDB 连接
  Java 连接 MongoDB 服务器,与我们常用的连接关系型数据库方式类似!
  标准 URI 连接语法: mongodb://username:password@host1:port1,host2:port2,...,hostN:portN/database?options
  参数说明: mongodb:// :这是固定的格式,必须要指定username:password@ :可选项,如果设置,在连接数据库服务器之后,驱动都会尝试登录这个数据库host1:port1 :主机IP和端口号,必须指定至少一个host。如果要连接复制集,请指定多个主机地址/database :如果指定了username:password@ ,连接时会验证并登录指定数据库。若不指定,默认打开 test 数据库?options :连接可选项,例如connectTimeoutMS=5000ms ,表示连接等待时间最长 5 秒
  例如,无密码连接 MongoDB mongodb://127.0.0.1:27017
  使用用户名 test ,密码test 登录 MongoDB 的test_db 数据库mongodb://test:test@127.0.0.1:27017/test_db
  无密码连接指定三台服务器 (端口 27017, 27018, 和27019) mongodb://127.0.0.1:27017,127.0.0.1:27018,127.0.0.1:27019 2.2、添加依赖包
  和关系型数据库操作一样,在 Java 程序中如果要使用 MongoDB,先要添加对应的 MongoDB JDBC 驱动器,然后才能继续操作!
  在选择的版本号的时候,注意需要和服务器中的安装版本匹配,具体的版本号选择可以从如下地址中获取到最新的版本:mongo-java-driver      org.mongodb     mongo-java-driver     3.12.7  2.3、连接数据库
  连接数据库的 Java 代码如下: private static MongoClient mongoClient;  static {     try {         //连接到MongoDB服务 如果是远程连接可以替换"localhost"为服务器所在IP地址         mongoClient = MongoClients.create("mongodb://test:test@127.0.0.1:27017/test_db");         System.out.println("Connect to database successfully");     } catch (Exception e) {         System.err.println( e.getClass().getName() + ": " + e.getMessage() );     } }
  上文中采用的是用户名和密码方式登录数据库,因为数据库已经开启了权限验证,因此需要通过用户名和密码才能登录。 2.4、创建集合
  com.mongodb.client 包里面都帮我们集成好了大部分常用的 api,我们可以通过MongoDatabase 类中的createCollection() 方法来创建集合。
  创建一个 tb_role 集合,代码片段如下:/**  * 创建集合  * @param args  */ public static void main(String[] args) {     // 连接到数据库     MongoDatabase mongoDatabase = mongoClient.getDatabase("test_db");     System.out.println("Connect to database successfully");     mongoDatabase.createCollection("tb_role");     System.out.println("集合创建成功"); }
  如果想删除集合,操作也很简单! /**  * 删除集合  * @param args  */ public static void main(String[] args) {     // 连接到数据库     MongoDatabase mongoDatabase = mongoClient.getDatabase("test_db");     System.out.println("Connect to database successfully");     mongoDatabase.getCollection("tb_role").drop();     System.out.println("集合 tb_role 删除成功"); } 2.5、创建文档
  我们可以通过 MongoCollection 类中的insertMany() 方法来插入一个文档。
  向 tb_role 集合中插入文档,代码片段如下:/**  * 插入文档  * @param args  */ public static void main(String[] args) {     // 连接到数据库     MongoDatabase mongoDatabase = mongoClient.getDatabase("test_db");     System.out.println("Connect to database successfully");     //获取集合     MongoCollection collection = mongoDatabase.getCollection("tb_role");      //向集合中插入文档     Document document = new Document("name", "管理员").             append("code", "manager").             append("sort", 100);     List documents = new ArrayList<>();     documents.add(document);     collection.insertMany(documents);     System.out.println("文档插入成功"); } 2.6、更新文档
  我们可以通过 MongoCollection 类中的updateMany() 方法来更新集合中的文档。
  更新 tb_role 集合中的指定文档信息,代码片段如下:/**  * 更新文档  * @param args  */ public static void main(String[] args) {     // 连接到数据库     MongoDatabase mongoDatabase = mongoClient.getDatabase("test_db");     System.out.println("Connect to database successfully");     //获取集合     MongoCollection collection = mongoDatabase.getCollection("tb_role");      //更新文档     collection.updateMany(Filters.eq("code", "manager"), new Document("$set",new Document("name","经理")));      //遍历所有文档     FindIterable findIterable = collection.find();     MongoCursor mongoCursor = findIterable.iterator();     while(mongoCursor.hasNext()){         System.out.println(mongoCursor.next());     } }
  上文操作类似于 SQL语句中的 update tb_role set name = "经理" where code = "manager" !2.7、删除文档
  我们可以通过 MongoCollection 类中的deleteOne() 或者deleteMany 方法来删除集合中的文档。
  删除 tb_role 集合中的指定文档信息,代码片段如下:/**  * 删除文档  * @param args  */ public static void main(String[] args) {     // 连接到数据库     MongoDatabase mongoDatabase = mongoClient.getDatabase("test_db");     System.out.println("Connect to database successfully");     //获取集合     MongoCollection collection = mongoDatabase.getCollection("tb_role");      //删除符合条件的第一个文档     collection.deleteOne(Filters.eq("code", "manager"));     //删除所有符合条件的文档     collection.deleteMany (Filters.eq("code", "manager"));      //遍历所有文档     FindIterable findIterable = collection.find();     MongoCursor mongoCursor = findIterable.iterator();     while(mongoCursor.hasNext()){         System.out.println(mongoCursor.next());     } }
  在这里需要注意一下,在删除的时候,官方推荐尽可能先查询一下这个数据是否存在,如果存在,然后在执行删除操作,可以调用 findOneAndDelete() 方法进行删除!2.8、查询文档
  MongoCollection 类中提供了非常丰富的检索文档的方法,例如,我们可以通过find() 方法来获取集合中的所有文档。
  检索 tb_role 集合中的文档信息,代码片段如下:/**  * 查询文档  * @param args  */ public static void main(String[] args) {     // 连接到数据库     MongoDatabase mongoDatabase = mongoClient.getDatabase("test_db");     System.out.println("Connect to database successfully");     //获取集合     MongoCollection collection = mongoDatabase.getCollection("tb_role");      //遍历所有文档     FindIterable findIterable = collection.find();     MongoCursor mongoCursor = findIterable.iterator();     while(mongoCursor.hasNext()){         System.out.println(mongoCursor.next());     }      //查询当前集合所有文档数量     long count = collection.countDocuments();     System.out.println("当前文档数量:" + count);      //带条件遍历文档     FindIterable documentFindIterable = collection.find(Filters.eq("code", "manager"));     MongoCursor documentMongoCursor = documentFindIterable.iterator();     while(documentMongoCursor.hasNext()){         System.out.println(documentMongoCursor.next());     } } 三、SpringBoot 整合 MongoDB
  采用 SpringBoot 来对接 MongoDB,可以说极其简单,下面就以常用的几个操作为例来介绍,过程如下! 3.1、创建 SpringBoot 工程,添加 MongoDB 依赖包      org.springframework.boot     spring-boot-starter-parent     2.1.0.RELEASE        org.springframework.boot     spring-boot-starter-data-mongodb  3.2、添加配置文件
  在 application.properties 文件中添加mongodb 配置#配置数据库连接地址 spring.data.mongodb.uri=mongodb://test123:test123@127.0.0.1:27017/test_db 3.3、创建实体类
  创建用于示例中测试的实体类 Person 。
  其中注解 @Document(collection="persons") 用于指定当前文档属于集合persons 。
  注解 @Id 表示当前id 字段属于主键类型。/**  * 使用@Document注解指定集合名称  */ @Document(collection="persons") public class Person implements Serializable {     private static final long serialVersionUID = -3258839839160856613L;   /**      * 使用@Id注解指定MongoDB中的 _id 主键      */     @Id     private Long id;      private String userName;      private String passWord;      private Integer age;      private Date createTime;      //...get/set      @Override     public String toString() {         return "Person{" +                 "id=" + id +                 ", userName="" + userName + """ +                 ", passWord="" + passWord + """ +                 ", age=" + age +                 ", createTime=" + createTime +                 "}";     } } 3.4、操作 MongoDB
  Springboot 操作 MongoDB 有两种方式。 第一种方式是采用 Springboot 官方推荐的 JPA 方式,这种操作方式,使用简单但是灵活性比较差。 第二种方式是采用 Spring Data MongoDB 封装的 MongoDB 官方 Java 驱动 MongoTemplate 对 MongoDB 进行操作,这种方式非常灵活,能满足绝大部分需求。
  本文将采用第二种方式进行介绍! 3.5、插入文档
  MongoTemplate 提供了insert() 方法,用于插入文档,示例代码如下:用于插入文档
  没指定集合名称时,会取 @Document 注解中的集合名称@RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;      /**      * 插入文档      * @throws Exception      */     @Test     public void insert() throws Exception {         Person person =new Person();         person.setId(1l);         person.setUserName("张三");         person.setPassWord("123456");         person.setCreateTime(new Date());         mongoTemplate.insert(person);     } } 自定义集合名称,插入文档 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;      /**      * 自定义集合,插入文档      * @throws Exception      */     @Test     public void insertCustomCollection() throws Exception {         Person person =new Person();         person.setId(1l);         person.setUserName("张三");         person.setPassWord("123456");         person.setCreateTime(new Date());         mongoTemplate.insert(person, "custom_person");     } } 自定义集合,批量插入文档
  如果采用批量插入文档,必须指定集合名称 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;      /**      * 自定义集合,批量插入文档      * @throws Exception      */     @Test     public void insertBatch() throws Exception {         List personList = new ArrayList<>();         Person person1 =new Person();         person1.setId(10l);         person1.setUserName("张三");         person1.setPassWord("123456");         person1.setCreateTime(new Date());         personList.add(person1);          Person person2 =new Person();         person2.setId(11l);         person2.setUserName("李四");         person2.setPassWord("123456");         person2.setCreateTime(new Date());         personList.add(person2);          mongoTemplate.insert(personList, "custom_person");     } } 3.6、存储文档
  MongoTemplate 提供了save() 方法,用于存储文档。
  在存储文档的时候会通过主键ID进行判断,如果存在就更新,否则就插入,示例代码如下: 存储文档,如果没有插入,否则通过 主键ID 更新@RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;      /**      * 存储文档,如果没有插入,否则更新      * @throws Exception      */     @Test     public void save() throws Exception {         Person person =new Person();         person.setId(13l);         person.setUserName("八八");         person.setPassWord("123456");         person.setAge(40);         person.setCreateTime(new Date());         mongoTemplate.save(person);     } } 自定义集合,存储文档 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;      /**      * 自定义集合,存储文档      * @throws Exception      */     @Test     public void saveCustomCollection() throws Exception {         Person person =new Person();         person.setId(1l);         person.setUserName("张三");         person.setPassWord("123456");         person.setCreateTime(new Date());         mongoTemplate.save(person, "custom_person");     } } 3.7、更新文档
  MongoTemplate 提供了updateFirst() 和updateMulti() 方法,用于更新文档,示例代码如下:更新文档,匹配查询到的文档数据中的第一条数据 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;      /**      * 更新文档,匹配查询到的文档数据中的第一条数据      * @throws Exception      */     @Test     public void updateFirst() throws Exception {         //更新对象         Person person =new Person();         person.setId(1l);         person.setUserName("张三123");         person.setPassWord("123456");         person.setCreateTime(new Date());          //更新条件         Query query= new Query(Criteria.where("id").is(person.getId()));          //更新值         Update update= new Update().set("userName", person.getUserName()).set("passWord", person.getPassWord());         //更新查询满足条件的文档数据(第一条)         UpdateResult result =mongoTemplate.updateFirst(query,update, Person.class);         if(result!=null){             System.out.println("更新条数:" + result.getMatchedCount());         }     } } 更新文档,匹配查询到的文档数据中的所有数据 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;      /**      * 更新文档,匹配查询到的文档数据中的所有数据      * @throws Exception      */     @Test     public void updateMany() throws Exception {         //更新对象         Person person =new Person();         person.setId(1l);         person.setUserName("张三");         person.setPassWord("123456");         person.setCreateTime(new Date());          //更新条件         Query query= new Query(Criteria.where("id").is(person.getId()));          //更新值         Update update= new Update().set("userName", person.getUserName()).set("passWord", person.getPassWord());         //更新查询满足条件的文档数据(全部)         UpdateResult result = mongoTemplate.updateMulti(query, update, Person.class);         if(result!=null){             System.out.println("更新条数:" + result.getMatchedCount());         }     } } 3.8、删除文档
  MongoTemplate 提供了remove() 、findAndRemove() 和findAllAndRemove() 方法,用于删除文档,示例代码如下:删除符合条件的所有文档 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;      /**      * 删除符合条件的所有文档      * @throws Exception      */     @Test     public void remove() throws Exception {         Person person =new Person();         person.setId(1l);         person.setUserName("张三");         person.setPassWord("123456");         person.setCreateTime(new Date());          Query query = new Query(Criteria.where("userName").is(person.getUserName()));         DeleteResult result = mongoTemplate.remove(query, Person.class);         System.out.println("删除条数:" + result.getDeletedCount());     } } 删除符合条件的单个文档,并返回删除的文档 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;      /**      * 删除符合条件的单个文档,并返回删除的文档      * @throws Exception      */     @Test     public void findAndRemove() throws Exception {         Person person =new Person();         person.setId(1l);         person.setUserName("张三");         person.setPassWord("123456");         person.setCreateTime(new Date());          Query query = new Query(Criteria.where("id").is(person.getId()));         Person result = mongoTemplate.findAndRemove(query, Person.class);         System.out.println("删除的文档数据:" + result.toString());     } } 删除符合条件的所有文档,并返回删除的文档 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;      /**      * 删除符合条件的所有文档,并返回删除的文档      * @throws Exception      */     @Test     public void findAllAndRemove() throws Exception {         Person person =new Person();         person.setId(1l);         person.setUserName("张三");         person.setPassWord("123456");         person.setCreateTime(new Date());          Query query = new Query(Criteria.where("id").is(person.getId()));         List result = mongoTemplate.findAllAndRemove(query, Person.class);         System.out.println("删除的文档数据:" + result.toString());     } } 3.9、查询文档
  MongoTemplate 提供了非常多的文档查询方法,日常开发中用的最多的就是find() 方法,示例代码如下:查询集合中的全部文档数据 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;      /**      * 查询集合中的全部文档数据      * @throws Exception      */     @Test     public void findAll() throws Exception {         List result = mongoTemplate.findAll(Person.class);         System.out.println("查询结果:" + result.toString());     } } 查询集合中指定的ID文档数据 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;      /**      * 查询集合中指定的ID文档数据      * @throws Exception      */     @Test     public void findById() {         long id = 1l;         Person result = mongoTemplate.findById(id, Person.class);         System.out.println("查询结果:" + result.toString());     } } 根据条件查询集合中符合条件的文档,返回第一条数据 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;      /**      * 根据条件查询集合中符合条件的文档,返回第一条数据      */     @Test     public void findOne() {         String userName = "张三";         Query query = new Query(Criteria.where("userName").is(userName));         Person result = mongoTemplate.findOne(query, Person.class);         System.out.println("查询结果:" + result.toString());     } } 根据条件查询集合中符合条件的文档 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;      /**      * 根据条件查询集合中符合条件的文档      */     @Test     public void findByCondition() {         String userName = "张三";         Query query = new Query(Criteria.where("userName").is(userName));         List result = mongoTemplate.find(query, Person.class);         System.out.println("查询结果:" + result.toString());     } } 根据【AND】关联多个查询条件,查询集合中的文档数据 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;      /**      * 根据【AND】关联多个查询条件,查询集合中的文档数据      */     @Test     public void findByAndCondition() {         // 创建条件         Criteria criteriaUserName = Criteria.where("userName").is("张三");         Criteria criteriaPassWord = Criteria.where("passWord").is("123456");         // 创建条件对象,将上面条件进行 AND 关联         Criteria criteria = new Criteria().andOperator(criteriaUserName, criteriaPassWord);         // 创建查询对象,然后将条件对象添加到其中         Query query = new Query(criteria);         List result = mongoTemplate.find(query, Person.class);         System.out.println("查询结果:" + result.toString());     } } 根据【OR】关联多个查询条件,查询集合中的文档数据 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;      /**      * 根据【OR】关联多个查询条件,查询集合中的文档数据      */     @Test     public void findByOrCondition() {         // 创建条件         Criteria criteriaUserName = Criteria.where("userName").is("张三");         Criteria criteriaPassWord = Criteria.where("passWord").is("123456");         // 创建条件对象,将上面条件进行 OR 关联         Criteria criteria = new Criteria().orOperator(criteriaUserName, criteriaPassWord);         // 创建查询对象,然后将条件对象添加到其中         Query query = new Query(criteria);         List result = mongoTemplate.find(query, Person.class);         System.out.println("查询结果:" + result.toString());     } } 根据【IN】关联多个查询条件,查询集合中的文档数据 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;      /**      * 根据【IN】关联多个查询条件,查询集合中的文档数据      */     @Test     public void findByInCondition() {         // 设置查询条件参数         List ids = Arrays.asList(1l, 10l, 11l);         // 创建条件         Criteria criteria = Criteria.where("id").in(ids);         // 创建查询对象,然后将条件对象添加到其中         Query query = new Query(criteria);         List result = mongoTemplate.find(query, Person.class);         System.out.println("查询结果:" + result.toString());     } } 根据【逻辑运算符】查询集合中的文档数据 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;      /**      * 根据【逻辑运算符】查询集合中的文档数据      */     @Test     public void findByOperator() {         // 设置查询条件参数         int min = 20;         int max = 35;         Criteria criteria = Criteria.where("age").gt(min).lte(max);         // 创建查询对象,然后将条件对象添加到其中         Query query = new Query(criteria);         List result = mongoTemplate.find(query, Person.class);         System.out.println("查询结果:" + result.toString());     } } 根据【正则表达式】查询集合中的文档数据 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;      /**      * 根据【正则表达式】查询集合中的文档数据      */     @Test     public void findByRegex() {         // 设置查询条件参数         String regex = "^张*";         Criteria criteria = Criteria.where("userName").regex(regex);         // 创建查询对象,然后将条件对象添加到其中         Query query = new Query(criteria);         List result = mongoTemplate.find(query, Person.class);         System.out.println("查询结果:" + result.toString());     } } 根据条件查询集合中符合条件的文档,获取其文档列表并排序 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;      /**      * 根据条件查询集合中符合条件的文档,获取其文档列表并排序      */     @Test     public void findByConditionAndSort() {         String userName = "张三";         Query query = new Query(Criteria.where("userName").is(userName)).with(Sort.by("age"));         List result = mongoTemplate.find(query, Person.class);         System.out.println("查询结果:" + result.toString());     } } 根据单个条件查询集合中的文档数据,并按指定字段进行排序与限制指定数目 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;     /**      * 根据单个条件查询集合中的文档数据,并按指定字段进行排序与限制指定数目      */     @Test     public void findByConditionAndSortLimit() {         String userName = "张三";         //从第一行开始,查询2条数据返回         Query query = new Query(Criteria.where("userName").is(userName)).with(Sort.by("createTime")).limit(2).skip(1);         List result = mongoTemplate.find(query, Person.class);         System.out.println("查询结果:" + result.toString());     } } 统计集合中符合【查询条件】的文档【数量】 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;     /**      * 统计集合中符合【查询条件】的文档【数量】      */     @Test     public void countNumber() {         // 设置查询条件参数         String regex = "^张*";         Criteria criteria = Criteria.where("userName").regex(regex);         // 创建查询对象,然后将条件对象添加到其中         Query query = new Query(criteria);         long count = mongoTemplate.count(query, Person.class);         System.out.println("统计结果:" + count);     } } 4.0、创建索引
  索引在所有的数据库中,暂居的位置非常重要,例如当你检索一张上百万的数据表的时候,如果没走索引,查询效率会极其缓慢,对于 MongoDB 来说,同样如此。
  示例如下: 创建升序索引 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;      /**      * 创建升序索引      */     @Test     public void createAscendingIndex() {         // 设置字段名称         String field = "userName";         // 创建索引         mongoTemplate.getCollection("persons").createIndex(Indexes.ascending(field));     } } 移除索引 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;     /**      * 根据索引名称移除索引      */     @Test     public void removeIndex() {         // 设置字段名称         String field = "userName";         // 删除索引         mongoTemplate.getCollection("persons").dropIndex(field);     } } 查询集合中所有的索引 @RunWith(SpringRunner.class) @SpringBootTest public class PersonServiceTest {      @Autowired     private MongoTemplate mongoTemplate;     /**      * 查询集合中所有的索引      */     @Test     public void getIndexAll() {         // 获取集合中所有列表         ListIndexesIterable indexList = mongoTemplate.getCollection("persons").listIndexes();         // 获取集合中全部索引信息         for (Document document : indexList) {             System.out.println("索引列表:" + document);         }     } } 我们还可以通过在实体类上加注解方式来创建索引 /**  * 使用@Document注解指定集合名称  */ @Document(collection="persons") public class Person implements Serializable {     private static final long serialVersionUID = -3258839839160856613L;   /**      * 使用@Id注解指定MongoDB中的 _id 主键      */     @Id     private Long id;      private String userName;      private String passWord;      private Integer age;   /**      * 创建一个5秒之后文档自动删除的索引      */     @Indexed(expireAfterSeconds=5)     private Date createTime;      //...get/set      @Override     public String toString() {         return "Person{" +                 "id=" + id +                 ", userName="" + userName + """ +                 ", passWord="" + passWord + """ +                 ", age=" + age +                 ", createTime=" + createTime +                 "}";     } } 4.1、引入 MongoDB 中的事务
  单节点 mongodb 不支持事务,需要搭建 MongoDB 复制集。 /**  * 配置事务管理器  *  */ @Configuration public class TransactionConfig {      @Bean     MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) {         return new MongoTransactionManager(dbFactory);     }  }
  事务服务测试! @Service public class TransactionExample {      @Autowired     private MongoTemplate mongoTemplate;      @Transactional(rollbackFor = Exception.class)     public Object transactionTest(){         Person person =new Person();         person.setId(1l);         person.setUserName("张三");         person.setPassWord("123456");         person.setCreateTime(new Date());         Person newPerson = mongoTemplate.insert(person);         // 抛出异常,观察数据是否进行回滚         if(1 == 1){             throw new RuntimeException("异常");         }         return newPerson;     } } 四、小结
  本文主要围绕 MongoDB 的 Java 客户端使用进行基本的增删改查操作介绍,在实际的业务场景中,可能还需要用到聚合函数等高级查询,大家如果有这种需求,可以访问如下地址获取更加详细的 api 文档介绍:MongoDB 文档查询 api 介绍
  demo获取地址:https://github.com/justdojava/springboot-example-mongodb 五、参考
  1、菜鸟教程 - mongodb
  2、超级小豆丁 - MongoDB 介绍

英特尔Arc显卡发布在即,NVIDIA和AMD谁最不想看到?两天前Intel发布了显卡品牌Arc以及相关的一些架构和技术,在架构方面可以确认的是Arc显卡将会集成光线追踪和张量计算加速,是可以和NVIDIAAmpere相提并论的架构,当然这为什么大多数投资人投不出伟大公司最近听闻国内投资人开始疯狂追逐硬核科技,生物医药方面的赛道,开始更大程度上鄙夷商业模式创新的初创企业。国内投资者很多一直都对商业模式创新的企业有一种轻蔑态度,在项目融资的时候,还会尼康Z9真机亮相东京奥运会依然疑点重重在今年的3月10日,尼康抢先于佳能公布了无反旗舰机Z9的研发消息,当时透露的一些先导细节包括了Z9将采用全新的CMOS传感器支持8K视频,定位于当前旗舰级单反D6的替代。在这之后,不是PSVR2?索尼新一代VR头显渲染图疑似泄露编译VR陀螺就在我们都确信索尼正在准备的新一代VR头显是PSVR2时,国外有博主爆出索尼确实正在准备下一代头显,但却并不是PSVR2,而是为兼容Xperia1II和Xperia1I有赞新零售鞋服商家私域用户达1。5亿,首个鞋服行业私域解决方案一年一度的双十一即将来临,作为双十一的主力军,鞋服行业已经全面进入新零售时代。如何加快数字化转型的速度,完善数字营销一体化建设,成为鞋服行业商家保持可持续增长的当务之急。10月21以太坊全网哈希率重回巅峰算力占用等同一千万片3060Ti根据最新的数字统计,目前以太坊的全网哈希率(或者说全网算力)已经达到了641。08THashs或者说641080000MHs,如果按照RTX3060Ti算力位60MHs为参考的话,IntelSapphireRapids处理器将集成HBM2E高速内存SapphireRapids是Intel下一代志强的架构代号,具有全新的微架构,集成八通道DDR5内存通道并且提供了PCIE5。0总线支持,用于取代目前的CooperLake等至强微软版DLSS?微软招募AI超分辨率技术工程师AMD在较早前发布了该公司的FSR超分辨率技术,该技术以纯空间的方式实现超分辨率,虽然画质较原生分辨率有一定距离,但是性能提升显著,将其应用在4K级别分辨率后能提供较高的流畅度。目扎克伯格Facebook2021年的XR投资总额将达到100亿美元编译VR陀螺10月26日,据外媒消息,Facebook在2021年第三季度财报电话会议上表示,预计今年的XR投资将超过100亿美元,并告知投资者,它计划在随后几年投入更多。Face大家想多了亚马逊否认将会在年内支持加密货币支付日前,本号发表的Amazon正在评估接纳比特币汇率波动问题是最大困扰一文提到了亚马逊正在物色加密货币支付的领导人,提到人们认为这标志着亚马逊有可能会很快提供加密货币作为全球支付手段谷歌CEOSundarPichai称该公司正在为AR进行必要的深度投资编译VR陀螺在Alphabet2021年第三季度财报电话会议上,谷歌CEOSundarPichai在被问及增强现实时分享了一些关于谷歌在AR领域工作的简要想法。与其他公司,即Fac
音乐制作四种麦克风类型动圈麦克风动圈话筒是话筒世界的主力军。它们便宜耐用并且在一些最常见的录音来源上听起来很棒。使用悬浮在磁铁场中的可移动感应线圈,动态麦克风就像扬声器一样反向工作!动圈话筒对瞬变做出响华为nova8SE4G正式发布搭载麒麟710A4G处理器,运行鸿蒙系统受到美国芯片制裁困扰的华为正式推出了nova8SE4G,这是一款仅支持4G网络的机型。华为nova8SE4G采用采用6。5英寸OLED屏幕,搭载仅支持4G的海思麒麟710A处理器,大男孩的玩具!华为VRGlass6DoF套装今晚0点开售很多人小时候都喜欢玩玩具,但随着年龄的增长,适合成年人并且感兴趣的玩具越来越少,尤其是男生,网络流传着这样一句话男人至死是少年,但很多人已经很难找回少年的感觉。不过,就算年纪不断增华为Mate50Pro渲染图200Hz无孔屏1亿长焦,这次苹果压力大了若不是受到了多轮制裁,现在的华为手机出货量应该可以攀升至全球第一,高端手机市场的份额也不会被迫让给苹果,很多花粉手握老华为机型,正在盼望着华为Mate50系列的发布,而就在近日,一最近想换手机,苹果12PM和华为Mate40P,买哪个好?还是选择华为mete40p吧!苹果手机非常有局限性,很多都不支持,少了很多玩机的乐趣!现在国产手机也是非常强悍,从硬件到系统都是非常不错的,流畅度也是非常棒!我是坚定的爱国者,无论小巨人易点云创始人纪鹏程一开始只想赚点生活费,没想到做出了一条产业链本报记者任晓宁北京报道乍一看上去,纪鹏程不像一个传统意义上公司老板的模样,帽衫牛仔裤加球鞋,鞋带和抽绳都是橙色,色系搭配统一,聊到高兴时两眼放光,和他12年前在清华大学读书时的模样芯片紧缺时代,索尼扩产影像传感器,占据市场高地受到国际政经环境的影响,全球半导体行业的供应链出现一些混乱,索尼也难免受到影响,影像及传感业务的营业利润微降至497亿日元。但索尼目前仍牢牢占据智能手机图像传感器市占率第一(48。湖南着力打造具有核心竞争力的科技创新高地来源人民网人民日报去年以来,湖南省着力推进关键核心技术攻关基础研究发展创新主体增量提质芙蓉人才行动创新平台建设创新生态优化科技成果转化七大计划,加快科技创新体系建设,全面塑造发展新你现在使用的手机需要更换了,你是选择华为还是苹果?首先说明一下,我个人从来不用苹果手机。即是我现在使用的不是华为手机,需要换手机了,从个人感情和国际大环境来说,也不会换用苹果手机。为了国家和个人的利益我仍然会换成华为手机。从小了说想改变银行,让你知道什么叫特许经营行业?今天港股中概又崩了,因为港媒报道明年3月就不能用互联网企业的二维码进行收付款了。这带来的影响肯定是很明显的,未来如果想要继续使用当然只能用银行的了。不知道最近大家发现没有互联网企业欧科云链斩获卓越科技服务企业奖鞭牛士报道11月25日,由经济观察报主办的新发展新秩序2021卓越金融企业盛典举行。论坛揭晓了年度卓越金融企业各个奖项,欧科云链获20202021年度卓越科技服务企业奖。欧科云链是