MongoDB---com.mongodb.client
1、概述
1.1、MongoDB 对数据的操作 分为 Read Operations(查询操作)、Write Operations(增、删、改);
1.2、MongoDB 提供 客户端 用 bulk 方式 执行 Write Operations(批量写操作);
1.3、
BulkWriteResult bulkWrite(List<? extends WriteModel<? extends TDocument>> requests);
bulkWrite() 参数要求 传入一个List,集合中元素类型是WriteModel(批量写的基类),有以下几个子类:
DeleteManyModel、DeleteOneModel、InsertOneModel、ReplaceOneModel、UpdateManyModel、UpdateOneModel...
bulkWrite() 返回值 BulkWriteResult ,代表一个成功批量写操作结果(封装了 操作结果的状态信息);
2、实战
<dependencies> <!-- https://mvnrepository.com/artifact/org.springframework.integration/spring-integration-mongodb --> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-mongodb</artifactId> <version>5.1.0.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver --> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.11.2</version> </dependency> </dependencies>
package com.springmongo; /** * @description: * @author: anpeiyong * @date: Created in 2020/1/14 15:41 * @since: */ public class Person { private String _id; private Integer age; private String name; public Person(String _id,Integer age,String name){ this._id=_id; this.age=age; this.name=name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String get_id() { return _id; } public void set_id(String _id) { this._id = _id; } @Override public String toString() { return this.age+":"+this.name; } }
package com.springmongo; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.model.*; import org.bson.Document; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.core.BulkOperations; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoDbFactory; import org.springframework.data.mongodb.core.index.Index; import org.springframework.data.mongodb.core.index.IndexInfo; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import java.util.ArrayList; import java.util.List; /** * @description: * @author: anpeiyong * @date: Created in 2019/11/11 19:19 * @since: */ public class SpringMongoTest { static MongoTemplate mongoTemplate; static MongoDbFactory mongoDbFactory; static MongoCollection<Document> collection; static { mongoDbFactory = new SimpleMongoDbFactory(new MongoClient(), "test"); mongoTemplate=new MongoTemplate(mongoDbFactory); collection=mongoTemplate.getCollection("p10"); } public static void main(String[] args) { //+++++++++++++++mongoTemplate使用+++++++++++++++++++++ testAddIndex(); testAdd(); testGet(); testUpdate(); testDelete(); //com.mongo.client使用(MongoCollection使用) testMongoClientAdd(); testMongoClientDelete(); testMongoClientUpdate(); } private static void testAddIndex() { //ensureIndex() 确保在该集合上存在该索引 Index index=new Index(); index.on("name", Sort.Direction.DESC); mongoTemplate.indexOps("p10").ensureIndex(index); } public static void testAdd(){ Person p1=new Person("1",12,"jack"); Person p2=new Person("2",12,"jack"); Person p3=new Person("3",12,"jack"); //批量操作API // BulkMode.UNORDERED:表示并行处理,遇到错误时能继续执行不影响其他操作; // BulkMode.ORDERED:表示顺序执行,遇到错误时会停止所有执行 BulkOperations operations=mongoTemplate.bulkOps(BulkOperations.BulkMode.ORDERED,"pplist"); //单条数据操作 //save 插入2条相同数据 不会出现 DuplicateKeyException mongoTemplate.save(p1,"p7"); mongoTemplate.save(p1,"p7"); //insert 插入2条相同数据 会出现 DuplicateKeyException mongoTemplate.insert(p2,"p2"); operations.insert(p1); operations.execute(); //批量数据操作 List<Person> personList=new ArrayList<>(); personList.add(p2); personList.add(p3); mongoTemplate.insert(personList,"plist"); operations.insert(personList); operations.execute(); } public static void testGet(){ //获取所有索引 List<IndexInfo> indexList=mongoTemplate.indexOps("p10").getIndexInfo(); System.out.println(indexList); //查找所有集合内容 List<Person> personList=mongoTemplate.findAll(Person.class,"p10"); System.out.println(personList); //复合条件查询 Criteria criteria=new Criteria(); criteria.orOperator(Criteria.where("age").is(12),Criteria.where("name").is("rose")); Query query1=new Query(criteria); List<Person> pp2List=mongoTemplate.find(query1,Person.class,"p10"); System.out.println(pp2List); //分页查询 Query query2=new Query(); query2.skip(0).limit(1); List<Person> pp3List=mongoTemplate.find(query2,Person.class,"p10"); System.out.println(pp3List); //模糊查询 Query query3=new Query(); query3.addCriteria(Criteria.where("name").regex("ja")); List<Person> pp4List=mongoTemplate.find(query3,Person.class,"p10"); System.out.println(pp4List); //条件查询 Query query=new Query(); query.addCriteria(Criteria.where("name").is("jj")); List<Person> ppList=mongoTemplate.find(query,Person.class,"p10"); System.out.println(ppList); } public static void testUpdate(){ BulkOperations operations=mongoTemplate.bulkOps(BulkOperations.BulkMode.ORDERED,"p1"); //单个修改 Query query=new Query(Criteria.where("_id").is("5e1d7442ebbc1a60259a61dd")); Update update=new Update(); update.set("age",13); update.set("name","lan"); //传统实现 mongoTemplate.updateFirst(query,update,"p1"); //BulkOperations实现 operations.updateOne(query,update); operations.execute(); //批量修改 Query query1=new Query(Criteria.where("name").regex("ja")); Update update1=new Update(); update1.set("age",16); update.set("name","rose"); mongoTemplate.updateMulti(query1,update1,"p1"); } public static void testDelete(){ Query query=new Query(Criteria.where("_id").is("5e1d76e0eacc6d52f2b581cd")); mongoTemplate.remove(query,Person.class,"p1"); } public static void testMongoClientAdd(){ //批量新增 Person person=new Person("5",22,"jj"); List<WriteModel<Document>> writeModelList=new ArrayList<>(); Document insertDocument=new Document(); insertDocument.put("_id",person.get_id()); insertDocument.put("age",person.getAge()); insertDocument.put("name",person.getName()); InsertOneModel<Document> insertOneModel=new InsertOneModel<>(insertDocument); writeModelList.add(insertOneModel); testAddIndex(); collection.bulkWrite(writeModelList); Person person2=new Person("7",20,"jjkk"); List<Document> documentList=new ArrayList<>(); Document insertDocument2=new Document(); insertDocument2.put("_id",person2.get_id()); insertDocument2.put("age",person2.getAge()); insertDocument2.put("name",person2.getName()); documentList.add(insertDocument2); testAddIndex(); collection.insertMany(documentList); //单条新增 Person person1=new Person("6",21,"jjj"); Document insertDocument1=new Document(); insertDocument1.put("_id",person1.get_id()); insertDocument1.put("age",person1.getAge()); insertDocument1.put("name",person1.getName()); testAddIndex(); collection.insertOne(insertDocument1); } public static void testMongoClientDelete(){ //批量删除 Document deleteDocument=new Document("_id","6"); List<WriteModel<Document>> writeModelList=new ArrayList<>(); //DeleteOneModel 至多删除一条匹配条件的记录 DeleteOneModel<Document> deleteOneModel=new DeleteOneModel<Document>(deleteDocument); writeModelList.add(deleteOneModel); //DeleteManyModel 删除匹配条件的多条数据 DeleteManyModel<Document> deleteManyModel=new DeleteManyModel<Document>(deleteDocument); writeModelList.add(deleteManyModel); collection.bulkWrite(writeModelList); Document deleteDocument2=new Document("name","jj"); collection.deleteMany(deleteDocument2); //单条删除 Document deleteDocument1=new Document("_id","7"); collection.deleteOne(deleteDocument1); } public static void testMongoClientUpdate(){ //单个修改 Document document=new Document("_id","5"); //---要修改的内容 Document updateContent=new Document("$set",new Document("name","sss")); //---第一个参数:修改的id、第二个参数:修改后内容 collection.updateOne(document,updateContent); //批量修改 List<WriteModel<Document>> writeModelList=new ArrayList<>(); Document document1=new Document("_id","6"); //---要修改的内容 Document updateContent1=new Document("$set",new Document("name","ccc")); //---第一个参数:要修改的id、 //---第二个参数:修改后的内容 UpdateOneModel<Document> updateOneModel=new UpdateOneModel<Document>(document1,updateContent1); //---第一个参数:要修改的id、 //---第二个参数:修改后的内容、 //---第三个参数:可选、不填也会默认生成一个,upset值为false(如果未查到需要更新的内容,什么也不做); //upset为true(将新的Document插入数据库[查询Document 与 更新Document的结合]) UpdateOneModel<Document> updateOneModel1=new UpdateOneModel<Document>(document1,updateContent1,new UpdateOptions().upsert(false)); writeModelList.add(updateOneModel); collection.bulkWrite(writeModelList); } }
posted on 2020-01-15 12:28 anpeiyong 阅读(4130) 评论(0) 编辑 收藏 举报