org.mongodb mongo-java-driver 3.12.10
package com.detail.util; import java.util.ArrayList; import java.util.List; import org.bson.Document; import org.bson.conversions.Bson; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; //mongodb 连接数据库工具类 public class MongoDBUtil { //不通过认证获取连接数据库对象 public static MongoDatabase getConnect(){ //连接到 mongodb 服务 MongoClient mongoClient = new MongoClient("服务器ip", 27017); //连接到数据库 MongoDatabase mongoDatabase = mongoClient.getDatabase("test"); //返回连接数据库对象 return mongoDatabase; } //需要密码认证方式连接 public static MongoDatabase getAuthConnect(){ Listadds = new ArrayList<>(); //ServerAddress()两个参数分别为 服务器地址 和 端口 ServerAddress serverAddress = new ServerAddress("服务器ip", 27017); adds.add(serverAddress); List credentials = new ArrayList<>(); //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码 MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("root", "test", "root".toCharArray()); credentials.add(mongoCredential); //通过连接认证获取MongoDB连接 MongoClient mongoClient = new MongoClient(adds, credentials); //连接到数据库 MongoDatabase mongoDatabase = mongoClient.getDatabase("test"); //返回连接数据库对象 return mongoDatabase; } //插入一个文档 public void insertOneTest(){ //获取数据库连接对象 MongoDatabase mongoDatabase = MongoDBUtil.getConnect(); //获取集合 MongoCollection collection = mongoDatabase.getCollection("user"); //要插入的数据 Document document = new Document("name","张三") .append("sex", "男") .append("age", 18); //插入一个文档 collection.insertOne(document); } //插入多个文档 public void insertManyTest(){ //获取数据库连接对象 MongoDatabase mongoDatabase = MongoDBUtil.getConnect(); //获取集合 MongoCollection collection = mongoDatabase.getCollection("user"); //要插入的数据 List list = new ArrayList<>(); for(int i = 1; i <= 3; i++) { Document document = new Document("name", "张三") .append("sex", "男") .append("age", 18); list.add(document); } //插入多个文档 collection.insertMany(list); } //删除与筛选器匹配的单个文档 public void deleteOneTest(){ //获取数据库连接对象 MongoDatabase mongoDatabase = MongoDBUtil.getConnect(); //获取集合 MongoCollection collection = mongoDatabase.getCollection("user"); //申明删除条件 Bson filter = Filters.eq("age",18); //删除与筛选器匹配的单个文档 collection.deleteOne(filter); } //删除与筛选器匹配的所有文档 public void deleteManyTest(){ //获取数据库连接对象 MongoDatabase mongoDatabase = MongoDBUtil.getConnect(); //获取集合 MongoCollection collection = mongoDatabase.getCollection("user"); //申明删除条件 Bson filter = Filters.eq("age",18); //删除与筛选器匹配的所有文档 collection.deleteMany(filter); } //修改单个文档 public void updateOneTest(){ //获取数据库连接对象 MongoDatabase mongoDatabase = MongoDBUtil.getConnect(); //获取集合 MongoCollection collection = mongoDatabase.getCollection("user"); //修改过滤器 Bson filter = Filters.eq("name", "张三"); //指定修改的更新文档 Document document = new Document("$set", new Document("age", 100)); //修改单个文档 collection.updateOne(filter, document); } //修改多个文档 public void updateManyTest(){ //获取数据库连接对象 MongoDatabase mongoDatabase = MongoDBUtil.getConnect(); //获取集合 MongoCollection collection = mongoDatabase.getCollection("user"); //修改过滤器 Bson filter = Filters.eq("name", "张三"); //指定修改的更新文档 Document document = new Document("$set", new Document("age", 100)); //修改多个文档 collection.updateMany(filter, document); } //查找集合中的所有文档 public void findTest(){ //获取数据库连接对象 // MongoDatabase mongoDatabase = MongoDBUtil.getAuthConnect(); MongoDatabase mongoDatabase = MongoDBUtil.getConnect(); //获取集合 MongoCollection collection = mongoDatabase.getCollection("customer"); //查找集合中的所有文档 FindIterable findIterable = collection.find(); MongoCursor cursor = findIterable.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } //指定查询过滤器查询 public void FilterfindTest(){ //获取数据库连接对象 MongoDatabase mongoDatabase = MongoDBUtil.getConnect(); //获取集合 MongoCollection collection = mongoDatabase.getCollection("user"); //指定查询过滤器 Bson filter = Filters.eq("name", "张三"); //指定查询过滤器查询 FindIterable findIterable = collection.find(filter); MongoCursor cursor = findIterable.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } //取出查询到的第一个文档 public void findFirstTest(){ //获取数据库连接对象 MongoDatabase mongoDatabase = MongoDBUtil.getConnect(); //获取集合 MongoCollection collection = mongoDatabase.getCollection("user"); //查找集合中的所有文档 FindIterable findIterable = collection.find(); //取出查询到的第一个文档 Document document = (Document) findIterable.first(); //打印输出 System.out.println(document); } public static void main(String[] args) { MongoDBUtil mongodb = new MongoDBUtil(); mongodb.findTest(); } }
懒得搭建,需要的话进扣扣裙索要,783092701
package com.yhzq.dao.repository; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Component; import com.yhzq.dao.entity.Customer; import java.util.List; /** *Title: 客户数据访问服务
*Description:抽象出接口层,目的是为了自定义规范; * 并且未声明的,使用时,父类的也能直接使用
* @author wangmoumo * @myblog www.681vip.com * @date 2022年10月18日 */ public interface BaseRepository extends MongoRepository{ Customer findByFirstName(String firstName); List findByLastName(String lastName); }
package com.yhzq.service; import org.springframework.data.domain.Example; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import com.yhzq.dao.entity.Customer; import com.yhzq.dao.repository.BaseRepository; import javax.annotation.Resource; import java.util.List; /** *Title: CustomerService.java
*Description: service操作mongodb
* @author wangmoumo * @myblog www.681vip.com * @date 2022年10月18日 */ @Service public class CustomerService{ @Resource private BaseRepository repository; /** * 保存客户 * @param customer 客户 * 第一种使用save的方式修改,一般这种只能修改单个。 * 这种修改的方式是通过id去修改,如果id不存在就新增一个, * 存在就修改为新传入的数据 */ public ListsaveAll(Iterable iterable) { return repository.saveAll(iterable); } /** * 保存客户 * @param customer 客户 */ public Customer save(Customer customer) { Customer save = repository.save(customer); return save; } /** * 删除所有的客户 */ public void deleteAll() { repository.deleteAll(); } /** * 删除所有的客户 */ public void deleteAll(Customer customer) { repository.delete(customer); } /** * 删除所有的客户 */ public void deleteAll(Iterable extends Customer> entities) { repository.deleteAll(entities); } /** * 删除所有的客户 */ public void deleteById(String id) { repository.deleteById(id); } /** * 查询所有客户列表 * @return 客户列表 */ public List findAll() { return repository.findAll(); } /** * 查询所有客户列表 * @return 客户列表 */ public Iterable findAll(Sort sort) { return repository.findAll(sort); } /** * 查询所有客户列表 * @return 客户列表 */ public Iterable findAll(Example example) { return repository.findAll(example); } /** * 查询所有客户列表 * @return 客户列表 */ public Iterable findAllById(Iterable ids) { return repository.findAllById(ids); } /** * 通过名查找某个客户 * @param firstName * @return */ public Customer findByFirstName(String firstName) { return repository.findByFirstName(firstName); } /** * 通过姓查找客户列表 * @param lastName * @return */ public List findByLastName(String lastName) { return repository.findByLastName(lastName); } }
package com.yhzq.controller; import java.util.List; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.yhzq.dao.entity.Customer; import com.yhzq.service.CustomerService; @RestController public class CustomerController{ private static final Logger log = LoggerFactory.getLogger(CustomerController.class); @Resource private CustomerService service; @RequestMapping("/customer") public Customer save(){ Customer customer = new Customer("wang","baoluo"); Customer save = service.save(customer); log.info("save:"+save); return save; } @RequestMapping("/list") public ListfindAll() { List findAll = service.findAll(); log.info("findAll:"+findAll); return findAll; } }
懒得搭建,需要的话进扣扣裙索要,783092701
package com.example.dao; import com.example.entity.MongodbTest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; 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 org.springframework.stereotype.Component; /** * create by wbl * 2023/02/08 */ @Component public class MongodbTestDao { @Autowired private MongoTemplate mongoTemplate; /** * 创建对象 * @param test */ public void save(MongodbTest test) { mongoTemplate.insert(test); } /** * 根据名字去查询对象 * @param name * @return */ public MongodbTest findOne(String name) { Query query = new Query(Criteria.where("name").is(name)); MongodbTest mgt = mongoTemplate.findOne(query,MongodbTest.class); return mgt; } /** * 修改对象 * @param test */ public void updateMongoDb(MongodbTest test) { Query query = new Query(Criteria.where("id").is(test.getId())); Update update = new Update().set("age",test.getAge()).set("name",test.getName()); mongoTemplate.updateFirst(query,update,MongodbTest.class); } /** * 删除对象 * @param id */ public void removeMongodb(String id) { Query query = new Query(Criteria.where("id").is(id)); mongoTemplate.remove(query,MongodbTest.class); } }
package com.example.service; import com.example.dao.MongodbTestDao; import com.example.entity.MongodbTest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * create by wbl * 2023/02/08 */ @Service public class MongodbTestService { @Autowired private MongodbTestDao mongodbTestDao; /** * 增加的方法 */ public void save(){ MongodbTest mongodbTest = new MongodbTest(); mongodbTest.setId(1); mongodbTest.setAge(19); mongodbTest.setName("招投标"); mongodbTestDao.save(mongodbTest); } /** * 修改的方法 */ public void update() { MongodbTest mongodbTest = new MongodbTest(); mongodbTest.setId(1); mongodbTest.setAge(20); mongodbTest.setName("国网商城"); mongodbTestDao.updateMongoDb(mongodbTest); } }
package com.example.controller; import com.example.service.MongodbTestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * create by wsh * 2019/10/30 */ @RestController public class MongodbTestController { @Autowired private MongodbTestService mongodbTestService; /** * 增加对象 */ @GetMapping("/save") public void save() { mongodbTestService.save(); } @GetMapping("/update") public void update() { mongodbTestService.update(); } @GetMapping("/delete") public void update2() { mongodbTestService.update(); } }
/** *Query query = new Query(); * query.addCriteria(Criteria.where("name").is(name)); * @param key * @return */ //把多个条件组合在一起 public static Criteria where(String key) { return new Criteria(key); } //封装查询条件 /**例如: * *创建匹配器,即如何使用查询条件 * ExampleMatcher matcher = ExampleMatcher.matching() //构建对象 * .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式:模糊查询 * .withIgnoreCase(true) //改变默认大小写忽略方式:忽略大小写 * .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains()) //标题采用“包含匹配”的方式查询 * .withIgnorePaths("pageNum", "pageSize"); //忽略属性,不参与查询 *创建实例 *Exampleexample = Example.of(student, matcher); *Query query = new Query(Criteria.byExample(example)); **/ public static Criteria byExample(Object example) { return byExample(Example.of(example)); } //封装查询条件 public static Criteria byExample(Example> example) { return (new Criteria()).alike(example); } //匹配文档 public static Criteria matchingDocumentStructure(MongoJsonSchema schema) { return (new Criteria()).andDocumentStructureMatches(schema); } //并且 public Criteria and(String key) { return new Criteria(this.criteriaChain, key); } //是 public Criteria is(@Nullable Object o) { if (!this.isValue.equals(NOT_SET)) { throw new InvalidMongoDbApiUsageException("Multiple 'is' values declared. You need to use 'and' with multiple criteria"); } else if (this.lastOperatorWasNot()) { throw new InvalidMongoDbApiUsageException("Invalid query: 'not' can't be used with 'is' - use 'ne' instead."); } else { this.isValue = o; return this; } } //用于匹配正则表达式 private boolean lastOperatorWasNot() { return !this.criteria.isEmpty() && "$not".equals(this.criteria.keySet().toArray()[this.criteria.size() - 1]); } //不等于 public Criteria ne(@Nullable Object o) { this.criteria.put("$ne", o); return this; } //小于 public Criteria lt(Object o) { this.criteria.put("$lt", o); return this; } //小于等于 public Criteria lte(Object o) { this.criteria.put("$lte", o); return this; } //大于 public Criteria gt(Object o) { this.criteria.put("$gt", o); return this; } //大于等于 public Criteria gte(Object o) { this.criteria.put("$gte", o); return this; } //包含 public Criteria in(Object... o) { if (o.length > 1 && o[1] instanceof Collection) { throw new InvalidMongoDbApiUsageException("You can only pass in one argument of type " + o[1].getClass().getName()); } else { this.criteria.put("$in", Arrays.asList(o)); return this; } } //包含 public Criteria in(Collection> c) { this.criteria.put("$in", c); return this; } //与in相反 public Criteria nin(Object... o) { return this.nin((Collection)Arrays.asList(o)); } //与in相反 public Criteria nin(Collection> o) { this.criteria.put("$nin", o); return this; } //取模(求余)运算 ,即:key对应的值%value==remainder(求余是否等于remainder) public Criteria mod(Number value, Number remainder) { List