0


java操作mongodb源码

文章目录

案例一:MongoClient最简单操作

1、优缺点

  • 优点:简单,快速测试实现
  • 缺点:不适合项目整合使用

2、添加依赖

<dependency><groupId>org.mongodb</groupId><artifactId>mongo-java-driver</artifactId><version>3.12.10</version></dependency>

3、源码

packagecom.detail.util;importjava.util.ArrayList;importjava.util.List;importorg.bson.Document;importorg.bson.conversions.Bson;importcom.mongodb.MongoClient;importcom.mongodb.MongoCredential;importcom.mongodb.ServerAddress;importcom.mongodb.client.FindIterable;importcom.mongodb.client.MongoCollection;importcom.mongodb.client.MongoCursor;importcom.mongodb.client.MongoDatabase;importcom.mongodb.client.model.Filters;//mongodb 连接数据库工具类publicclassMongoDBUtil{//不通过认证获取连接数据库对象publicstaticMongoDatabasegetConnect(){//连接到 mongodb 服务MongoClient mongoClient =newMongoClient("服务器ip",27017);//连接到数据库MongoDatabase mongoDatabase = mongoClient.getDatabase("test");//返回连接数据库对象return mongoDatabase;}//需要密码认证方式连接publicstaticMongoDatabasegetAuthConnect(){List<ServerAddress> adds =newArrayList<>();//ServerAddress()两个参数分别为 服务器地址 和 端口ServerAddress serverAddress =newServerAddress("服务器ip",27017);
        adds.add(serverAddress);List<MongoCredential> credentials =newArrayList<>();//MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码MongoCredential mongoCredential =MongoCredential.createScramSha1Credential("root","test","root".toCharArray());
        credentials.add(mongoCredential);//通过连接认证获取MongoDB连接MongoClient mongoClient =newMongoClient(adds, credentials);//连接到数据库MongoDatabase mongoDatabase = mongoClient.getDatabase("test");//返回连接数据库对象return mongoDatabase;}//插入一个文档publicvoidinsertOneTest(){//获取数据库连接对象MongoDatabase mongoDatabase =MongoDBUtil.getConnect();//获取集合MongoCollection<Document> collection = mongoDatabase.getCollection("user");//要插入的数据Document document =newDocument("name","张三").append("sex","男").append("age",18);//插入一个文档
        collection.insertOne(document);}//插入多个文档publicvoidinsertManyTest(){//获取数据库连接对象MongoDatabase mongoDatabase =MongoDBUtil.getConnect();//获取集合MongoCollection<Document> collection = mongoDatabase.getCollection("user");//要插入的数据List<Document> list =newArrayList<>();for(int i =1; i <=3; i++){Document document =newDocument("name","张三").append("sex","男").append("age",18);
            list.add(document);}//插入多个文档
        collection.insertMany(list);}//删除与筛选器匹配的单个文档publicvoiddeleteOneTest(){//获取数据库连接对象MongoDatabase mongoDatabase =MongoDBUtil.getConnect();//获取集合MongoCollection<Document> collection = mongoDatabase.getCollection("user");//申明删除条件Bson filter =Filters.eq("age",18);//删除与筛选器匹配的单个文档
        collection.deleteOne(filter);}//删除与筛选器匹配的所有文档publicvoiddeleteManyTest(){//获取数据库连接对象MongoDatabase mongoDatabase =MongoDBUtil.getConnect();//获取集合MongoCollection<Document> collection = mongoDatabase.getCollection("user");//申明删除条件Bson filter =Filters.eq("age",18);//删除与筛选器匹配的所有文档
        collection.deleteMany(filter);}//修改单个文档publicvoidupdateOneTest(){//获取数据库连接对象MongoDatabase mongoDatabase =MongoDBUtil.getConnect();//获取集合MongoCollection<Document> collection = mongoDatabase.getCollection("user");//修改过滤器Bson filter =Filters.eq("name","张三");//指定修改的更新文档Document document =newDocument("$set",newDocument("age",100));//修改单个文档
        collection.updateOne(filter, document);}//修改多个文档publicvoidupdateManyTest(){//获取数据库连接对象MongoDatabase mongoDatabase =MongoDBUtil.getConnect();//获取集合MongoCollection<Document> collection = mongoDatabase.getCollection("user");//修改过滤器Bson filter =Filters.eq("name","张三");//指定修改的更新文档Document document =newDocument("$set",newDocument("age",100));//修改多个文档
        collection.updateMany(filter, document);}//查找集合中的所有文档publicvoidfindTest(){//获取数据库连接对象//        MongoDatabase mongoDatabase = MongoDBUtil.getAuthConnect();MongoDatabase mongoDatabase =MongoDBUtil.getConnect();//获取集合MongoCollection<Document> collection = mongoDatabase.getCollection("customer");//查找集合中的所有文档FindIterable findIterable = collection.find();MongoCursor cursor = findIterable.iterator();while(cursor.hasNext()){System.out.println(cursor.next());}}//指定查询过滤器查询publicvoidFilterfindTest(){//获取数据库连接对象MongoDatabase mongoDatabase =MongoDBUtil.getConnect();//获取集合MongoCollection<Document> 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());}}//取出查询到的第一个文档publicvoidfindFirstTest(){//获取数据库连接对象MongoDatabase mongoDatabase =MongoDBUtil.getConnect();//获取集合MongoCollection<Document> collection = mongoDatabase.getCollection("user");//查找集合中的所有文档FindIterable findIterable = collection.find();//取出查询到的第一个文档Document document =(Document) findIterable.first();//打印输出System.out.println(document);}publicstaticvoidmain(String[] args){MongoDBUtil mongodb =newMongoDBUtil();
        mongodb.findTest();}}

案例二:继承MongoRepository

懒得搭建,需要的话进扣扣裙索要,783092701

1、优缺点

  • 优点:适合springboot项目整合,分层操作
  • 缺点:不支持过滤条件分组。即不支持过滤条件用 or(或) 来连接,所有的过滤条件,都是简单一层的用 and(并且) 连接不支持两个值的范围查询,如时间范围的查询

2、接口类继承MongoRepository

packagecom.yhzq.dao.repository;importorg.springframework.data.mongodb.repository.MongoRepository;importorg.springframework.stereotype.Component;importcom.yhzq.dao.entity.Customer;importjava.util.List;/**
 * <p>Title: 客户数据访问服务</p>
 * <p>Description:抽象出接口层,目的是为了自定义规范;
 *                      并且未声明的,使用时,父类的也能直接使用 </p>
 * @author wangmoumo
 * @myblog www.681vip.com
 * @date 2022年10月18日
 */publicinterfaceBaseRepositoryextendsMongoRepository<Customer,String>{CustomerfindByFirstName(String firstName);List<Customer>findByLastName(String lastName);}

3、service类注入接口BaseRepository

packagecom.yhzq.service;importorg.springframework.data.domain.Example;importorg.springframework.data.domain.Sort;importorg.springframework.stereotype.Service;importcom.yhzq.dao.entity.Customer;importcom.yhzq.dao.repository.BaseRepository;importjavax.annotation.Resource;importjava.util.List;/**
 * <p>Title: CustomerService.java</p>
 * <p>Description: service操作mongodb</p>
 * @author wangmoumo
 * @myblog www.681vip.com
 * @date 2022年10月18日
 */@ServicepublicclassCustomerService{@ResourceprivateBaseRepository repository;/**
     * 保存客户
     * @param customer 客户
     * 第一种使用save的方式修改,一般这种只能修改单个。
     * 这种修改的方式是通过id去修改,如果id不存在就新增一个,
     * 存在就修改为新传入的数据
     */publicList<Customer>saveAll(Iterable<Customer> iterable){return repository.saveAll(iterable);}/**
     * 保存客户
     * @param customer 客户
     */publicCustomersave(Customer customer){Customer save = repository.save(customer);return save;}/**
     * 删除所有的客户
     */publicvoiddeleteAll(){
        repository.deleteAll();}/**
     * 删除所有的客户
     */publicvoiddeleteAll(Customer customer){
        repository.delete(customer);}/**
     * 删除所有的客户
     */publicvoiddeleteAll(Iterable<?extendsCustomer> entities){
        repository.deleteAll(entities);}/**
     * 删除所有的客户
     */publicvoiddeleteById(String id){
        repository.deleteById(id);}/**
     * 查询所有客户列表
     * @return 客户列表
     */publicList<Customer>findAll(){return repository.findAll();}/**
     * 查询所有客户列表
     * @return 客户列表
     */publicIterable<Customer>findAll(Sort sort){return repository.findAll(sort);}/**
     * 查询所有客户列表
     * @return 客户列表
     */publicIterable<Customer>findAll(Example<Customer> example){return repository.findAll(example);}/**
     * 查询所有客户列表
     * @return 客户列表
     */publicIterable<Customer>findAllById(Iterable<String> ids){return repository.findAllById(ids);}/**
     * 通过名查找某个客户
     * @param firstName
     * @return
     */publicCustomerfindByFirstName(String firstName){return repository.findByFirstName(firstName);}/**
     * 通过姓查找客户列表
     * @param lastName
     * @return
     */publicList<Customer>findByLastName(String lastName){return repository.findByLastName(lastName);}}

4、controller类注入service类

packagecom.yhzq.controller;importjava.util.List;importjavax.annotation.Resource;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;importcom.yhzq.dao.entity.Customer;importcom.yhzq.service.CustomerService;@RestControllerpublicclassCustomerController{privatestaticfinalLogger log =LoggerFactory.getLogger(CustomerController.class);@ResourceprivateCustomerService service;@RequestMapping("/customer")publicCustomersave(){Customer customer =newCustomer("wang","baoluo");Customer save = service.save(customer);
        log.info("save:"+save);return save;}@RequestMapping("/list")publicList<Customer>findAll(){List<Customer> findAll = service.findAll();
        log.info("findAll:"+findAll);return findAll;}}

案例三:使用MongoTemplate

懒得搭建,需要的话进扣扣裙索要,783092701

1、优缺点

  • 优点:擅长复杂查询,条件查询,聚合查询
  • 缺点:不支持返回固定字段

2、MongoTemplate结合Query

2.1 实现一:使用Criteria封装增删改查条件

在这里插入图片描述

2.1.1 Dao注入mongotemplate

packagecom.example.dao;importcom.example.entity.MongodbTest;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.data.mongodb.core.MongoTemplate;importorg.springframework.data.mongodb.core.query.Criteria;importorg.springframework.data.mongodb.core.query.Query;importorg.springframework.data.mongodb.core.query.Update;importorg.springframework.stereotype.Component;/**
 * create by wbl
 * 2023/02/08
 */@ComponentpublicclassMongodbTestDao{@AutowiredprivateMongoTemplate mongoTemplate;/**
     * 创建对象
     * @param test
     */publicvoidsave(MongodbTest test){
        mongoTemplate.insert(test);}/**
     * 根据名字去查询对象
     * @param name
     * @return
     */publicMongodbTestfindOne(String name){Query query =newQuery(Criteria.where("name").is(name));MongodbTest mgt = mongoTemplate.findOne(query,MongodbTest.class);return mgt;}/**
     * 修改对象
     * @param test
     */publicvoidupdateMongoDb(MongodbTest test){Query query =newQuery(Criteria.where("id").is(test.getId()));Update update =newUpdate().set("age",test.getAge()).set("name",test.getName());
        mongoTemplate.updateFirst(query,update,MongodbTest.class);}/**
     * 删除对象
     * @param id
     */publicvoidremoveMongodb(String id){Query query =newQuery(Criteria.where("id").is(id));
        mongoTemplate.remove(query,MongodbTest.class);}}

2.1.2 Service注入Dao

packagecom.example.service;importcom.example.dao.MongodbTestDao;importcom.example.entity.MongodbTest;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;/**
 * create by wbl
 * 2023/02/08
 */@ServicepublicclassMongodbTestService{@AutowiredprivateMongodbTestDao mongodbTestDao;/**
     * 增加的方法
     */publicvoidsave(){MongodbTest mongodbTest =newMongodbTest();
        mongodbTest.setId(1);
        mongodbTest.setAge(19);
        mongodbTest.setName("招投标");
        mongodbTestDao.save(mongodbTest);}/**
     * 修改的方法
     */publicvoidupdate(){MongodbTest mongodbTest =newMongodbTest();
        mongodbTest.setId(1);
        mongodbTest.setAge(20);
        mongodbTest.setName("国网商城");
        mongodbTestDao.updateMongoDb(mongodbTest);}}

2.1.3 Controller层注入service

packagecom.example.controller;importcom.example.service.MongodbTestService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RestController;/**
 * create by wsh
 * 2019/10/30
 */@RestControllerpublicclassMongodbTestController{@AutowiredprivateMongodbTestService mongodbTestService;/**
     * 增加对象
     */@GetMapping("/save")publicvoidsave(){
        mongodbTestService.save();}@GetMapping("/update")publicvoidupdate(){
        mongodbTestService.update();}@GetMapping("/delete")publicvoidupdate2(){
        mongodbTestService.update();}}

2.2 实现二:使用Example和Criteria封装查询条件

/**
     *Query query = new Query();
     * query.addCriteria(Criteria.where("name").is(name));
     * @param key
     * @return
     *///把多个条件组合在一起publicstaticCriteriawhere(String key){returnnewCriteria(key);}//封装查询条件/**例如:
         *
         *创建匹配器,即如何使用查询条件
         * ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
         *        .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式:模糊查询
         *        .withIgnoreCase(true) //改变默认大小写忽略方式:忽略大小写
         *        .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains()) //标题采用“包含匹配”的方式查询
         *        .withIgnorePaths("pageNum", "pageSize");  //忽略属性,不参与查询
         *创建实例
         *Example<Student> example = Example.of(student, matcher);
         *Query query = new Query(Criteria.byExample(example));
         **/publicstaticCriteriabyExample(Object example){returnbyExample(Example.of(example));}//封装查询条件publicstaticCriteriabyExample(Example<?> example){return(newCriteria()).alike(example);}//匹配文档publicstaticCriteriamatchingDocumentStructure(MongoJsonSchema schema){return(newCriteria()).andDocumentStructureMatches(schema);}//并且publicCriteriaand(String key){returnnewCriteria(this.criteriaChain, key);}//是publicCriteriais(@NullableObject o){if(!this.isValue.equals(NOT_SET)){thrownewInvalidMongoDbApiUsageException("Multiple 'is' values declared. You need to use 'and' with multiple criteria");}elseif(this.lastOperatorWasNot()){thrownewInvalidMongoDbApiUsageException("Invalid query: 'not' can't be used with 'is' - use 'ne' instead.");}else{this.isValue = o;returnthis;}}//用于匹配正则表达式privatebooleanlastOperatorWasNot(){return!this.criteria.isEmpty()&&"$not".equals(this.criteria.keySet().toArray()[this.criteria.size()-1]);}//不等于publicCriteriane(@NullableObject o){this.criteria.put("$ne", o);returnthis;}//小于publicCriterialt(Object o){this.criteria.put("$lt", o);returnthis;}//小于等于publicCriterialte(Object o){this.criteria.put("$lte", o);returnthis;}//大于publicCriteriagt(Object o){this.criteria.put("$gt", o);returnthis;}//大于等于publicCriteriagte(Object o){this.criteria.put("$gte", o);returnthis;}//包含publicCriteriain(Object... o){if(o.length >1&& o[1]instanceofCollection){thrownewInvalidMongoDbApiUsageException("You can only pass in one argument of type "+ o[1].getClass().getName());}else{this.criteria.put("$in",Arrays.asList(o));returnthis;}}//包含publicCriteriain(Collection<?> c){this.criteria.put("$in", c);returnthis;}//与in相反publicCriterianin(Object... o){returnthis.nin((Collection)Arrays.asList(o));}//与in相反publicCriterianin(Collection<?> o){this.criteria.put("$nin", o);returnthis;}//取模(求余)运算 ,即:key对应的值%value==remainder(求余是否等于remainder)publicCriteriamod(Number value,Number remainder){List<Object> l =newArrayList();
            l.add(value);
            l.add(remainder);this.criteria.put("$mod", l);returnthis;}//key键对应的集合包含col(all是包含关系,in是被包含关系)publicCriteriaall(Object... o){returnthis.all((Collection)Arrays.asList(o));}publicCriteriaall(Collection<?> o){this.criteria.put("$all", o);returnthis;}//匹配key所对应的集合的元素的指定数量(!!!不能进行像<5之类的范围匹配)publicCriteriasize(int s){this.criteria.put("$size", s);returnthis;}//查询字段是否存在(true:存在,false:不存在)publicCriteriaexists(boolean b){this.criteria.put("$exists", b);returnthis;}//基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配publicCriteriatype(int t){this.criteria.put("$type", t);returnthis;}publicCriteriatype(Type... types){Assert.notNull(types,"Types must not be null!");Assert.noNullElements(types,"Types must not contain null.");this.criteria.put("$type",Arrays.asList(types).stream().map(Type::value).collect(Collectors.toList()));returnthis;}//取反publicCriterianot(){returnthis.not((Object)null);}privateCriterianot(@NullableObject value){this.criteria.put("$not", value);returnthis;}//模糊查询用publicCriteriaregex(String re){returnthis.regex(re,(String)null);}publicCriteriaregex(String re,@NullableString options){returnthis.regex(this.toPattern(re, options));}publicCriteriaregex(Pattern pattern){Assert.notNull(pattern,"Pattern must not be null!");if(this.lastOperatorWasNot()){returnthis.not(pattern);}else{this.isValue = pattern;returnthis;}}publicCriteriaregex(BsonRegularExpression regex){if(this.lastOperatorWasNot()){returnthis.not(regex);}else{this.isValue = regex;returnthis;}}//privatePatterntoPattern(String regex,@NullableString options){Assert.notNull(regex,"Regex string must not be null!");returnPattern.compile(regex, options ==null?0:BSON.regexFlags(options));}publicCriteriawithinSphere(Circle circle){Assert.notNull(circle,"Circle must not be null!");this.criteria.put("$geoWithin",newGeoCommand(newSphere(circle)));returnthis;}publicCriteriawithin(Shape shape){Assert.notNull(shape,"Shape must not be null!");this.criteria.put("$geoWithin",newGeoCommand(shape));returnthis;}//输出接近某一地理位置的有序文档publicCriterianear(Point point){Assert.notNull(point,"Point must not be null!");this.criteria.put("$near", point);returnthis;}//指定地理空间查询从最近到最远返回文档的点。 MongoDB 使用球面几何计算$nearSphere的距离publicCriterianearSphere(Point point){Assert.notNull(point,"Point must not be null!");this.criteria.put("$nearSphere", point);returnthis;}//publicCriteriaintersects(GeoJson geoJson){Assert.notNull(geoJson,"GeoJson must not be null!");this.criteria.put("$geoIntersects", geoJson);returnthis;}//创建一个地理空间标准,与nearSphere一起使用publicCriteriamaxDistance(double maxDistance){if(!this.createNearCriteriaForCommand("$near","$maxDistance", maxDistance)&&!this.createNearCriteriaForCommand("$nearSphere","$maxDistance", maxDistance)){this.criteria.put("$maxDistance", maxDistance);returnthis;}else{returnthis;}}//mongodb地理空间计算逻辑publicCriteriaminDistance(double minDistance){if(!this.createNearCriteriaForCommand("$near","$minDistance", minDistance)&&!this.createNearCriteriaForCommand("$nearSphere","$minDistance", minDistance)){this.criteria.put("$minDistance", minDistance);returnthis;}else{returnthis;}}//匹配查询publicCriteriaelemMatch(Criteria c){this.criteria.put("$elemMatch", c.getCriteriaObject());returnthis;}//使用给定对象作为模式创建条件publicCriteriaalike(Example<?> sample){this.criteria.put("$example", sample);this.criteriaChain.add(this);returnthis;}//创建一个criteria ($jsonSchema),根据MongoJsonSchema定义的给定结构匹配文档publicCriteriaandDocumentStructureMatches(MongoJsonSchema schema){Assert.notNull(schema,"Schema must not be null!");Criteria schemaCriteria =newCriteria();
            schemaCriteria.criteria.putAll(schema.toDocument());returnthis.registerCriteriaChainElement(schemaCriteria);}publicCriteria.BitwiseCriteriaOperatorsbits(){returnnewCriteria.BitwiseCriteriaOperatorsImpl(this);}//或者/**
         * Aggregation agg = Aggregation.newAggregation(
         *     Aggregation.match(new Criteria()
         *             .andOperator(Criteria.where("onlineTime").gt(new Date()))
         *             .orOperator( Criteria.where("offlineTime").gt(new Date())
         *     ,Criteria.where("offlineTime").exists(false) ))
         * @param criteria
         * @return
         */publicCriteriaorOperator(Criteria... criteria){BasicDBList bsonList =this.createCriteriaList(criteria);returnthis.registerCriteriaChainElement((newCriteria("$or")).is(bsonList));}//非或者publicCriterianorOperator(Criteria... criteria){BasicDBList bsonList =this.createCriteriaList(criteria);returnthis.registerCriteriaChainElement((newCriteria("$nor")).is(bsonList));}//并且publicCriteriaandOperator(Criteria... criteria){BasicDBList bsonList =this.createCriteriaList(criteria);returnthis.registerCriteriaChainElement((newCriteria("$and")).is(bsonList));}privateCriteriaregisterCriteriaChainElement(Criteria criteria){if(this.lastOperatorWasNot()){thrownewIllegalArgumentException("operator $not is not allowed around criteria chain element: "+ criteria.getCriteriaObject());}else{this.criteriaChain.add(criteria);returnthis;}}@NullablepublicStringgetKey(){returnthis.key;}publicDocumentgetCriteriaObject(){if(this.criteriaChain.size()==1){return((Criteria)this.criteriaChain.get(0)).getSingleCriteriaObject();}elseif(CollectionUtils.isEmpty(this.criteriaChain)&&!CollectionUtils.isEmpty(this.criteria)){returnthis.getSingleCriteriaObject();}else{Document criteriaObject =newDocument();Iterator var2 =this.criteriaChain.iterator();while(var2.hasNext()){Criteria c =(Criteria)var2.next();Document document = c.getSingleCriteriaObject();Iterator var5 = document.keySet().iterator();while(var5.hasNext()){String k =(String)var5.next();this.setValue(criteriaObject, k, document.get(k));}}return criteriaObject;}}protectedDocumentgetSingleCriteriaObject(){Document document =newDocument();boolean not =false;Iterator var3 =this.criteria.entrySet().iterator();while(true){while(var3.hasNext()){Entry<String,Object> entry =(Entry)var3.next();String key =(String)entry.getKey();Object value = entry.getValue();if(requiresGeoJsonFormat(value)){
                        value =newDocument("$geometry", value);}if(not){Document notDocument =newDocument();
                        notDocument.put(key, value);
                        document.put("$not", notDocument);
                        not =false;}elseif("$not".equals(key)&& value ==null){
                        not =true;}else{
                        document.put(key, value);}}if(!StringUtils.hasText(this.key)){if(not){returnnewDocument("$not", document);}return document;}Document queryCriteria =newDocument();if(!NOT_SET.equals(this.isValue)){
                    queryCriteria.put(this.key,this.isValue);
                    queryCriteria.putAll(document);}else{
                    queryCriteria.put(this.key, document);}return queryCriteria;}}privateBasicDBListcreateCriteriaList(Criteria[] criteria){BasicDBList bsonList =newBasicDBList();Criteria[] var3 = criteria;int var4 = criteria.length;for(int var5 =0; var5 < var4;++var5){Criteria c = var3[var5];
                bsonList.add(c.getCriteriaObject());}return bsonList;}privatevoidsetValue(Document document,String key,Object value){Object existing = document.get(key);if(existing ==null){
                document.put(key, value);}else{thrownewInvalidMongoDbApiUsageException("Due to limitations of the com.mongodb.BasicDocument, you can't add a second '"+ key +"' expression specified as '"+ key +" : "+ value +"'. Criteria already contains '"+ key +" : "+ existing +"'.");}}privatebooleancreateNearCriteriaForCommand(String command,String operation,double maxDistance){if(!this.criteria.containsKey(command)){returnfalse;}else{Object existingNearOperationValue =this.criteria.get(command);if(existingNearOperationValue instanceofDocument){((Document)existingNearOperationValue).put(operation, maxDistance);returntrue;}elseif(existingNearOperationValue instanceofGeoJson){Document dbo =(newDocument("$geometry", existingNearOperationValue)).append(operation, maxDistance);this.criteria.put(command, dbo);returntrue;}else{returnfalse;}}}publicbooleanequals(Object obj){if(this== obj){returntrue;}elseif(obj !=null&&this.getClass().equals(obj.getClass())){Criteria that =(Criteria)obj;if(this.criteriaChain.size()!= that.criteriaChain.size()){returnfalse;}else{for(int i =0; i <this.criteriaChain.size();++i){Criteria left =(Criteria)this.criteriaChain.get(i);Criteria right =(Criteria)that.criteriaChain.get(i);if(!this.simpleCriteriaEquals(left, right)){returnfalse;}}returntrue;}}else{returnfalse;}}privatebooleansimpleCriteriaEquals(Criteria left,Criteria right){boolean keyEqual = left.key ==null? right.key ==null: left.key.equals(right.key);boolean criteriaEqual = left.criteria.equals(right.criteria);boolean valueEqual =this.isEqual(left.isValue, right.isValue);return keyEqual && criteriaEqual && valueEqual;}//判断是否相等privatebooleanisEqual(Object left,Object right){if(left ==null){return right ==null;}elseif(Pattern.class.isInstance(left)){if(!Pattern.class.isInstance(right)){returnfalse;}else{Pattern leftPattern =(Pattern)left;Pattern rightPattern =(Pattern)right;return leftPattern.pattern().equals(rightPattern.pattern())&& leftPattern.flags()== rightPattern.flags();}}else{returnObjectUtils.nullSafeEquals(left, right);}}publicinthashCode(){int result =17;int result = result +ObjectUtils.nullSafeHashCode(this.key);
            result +=this.criteria.hashCode();
            result +=ObjectUtils.nullSafeHashCode(this.isValue);return result;}privatestaticbooleanrequiresGeoJsonFormat(Object value){return value instanceofGeoJson|| value instanceofGeoCommand&&((GeoCommand)value).getShape()instanceofGeoJson;}privatestaticclassBitwiseCriteriaOperatorsImplimplementsCriteria.BitwiseCriteriaOperators{privatefinalCriteria target;BitwiseCriteriaOperatorsImpl(Criteria target){this.target = target;}publicCriteriaallClear(int numericBitmask){returnthis.numericBitmask("$bitsAllClear", numericBitmask);}publicCriteriaallClear(String bitmask){returnthis.stringBitmask("$bitsAllClear", bitmask);}publicCriteriaallClear(List<Integer> positions){returnthis.positions("$bitsAllClear", positions);}publicCriteriaallSet(int numericBitmask){returnthis.numericBitmask("$bitsAllSet", numericBitmask);}publicCriteriaallSet(String bitmask){returnthis.stringBitmask("$bitsAllSet", bitmask);}publicCriteriaallSet(List<Integer> positions){returnthis.positions("$bitsAllSet", positions);}publicCriteriaanyClear(int numericBitmask){returnthis.numericBitmask("$bitsAnyClear", numericBitmask);}publicCriteriaanyClear(String bitmask){returnthis.stringBitmask("$bitsAnyClear", bitmask);}publicCriteriaanyClear(List<Integer> positions){returnthis.positions("$bitsAnyClear", positions);}publicCriteriaanySet(int numericBitmask){returnthis.numericBitmask("$bitsAnySet", numericBitmask);}publicCriteriaanySet(String bitmask){returnthis.stringBitmask("$bitsAnySet", bitmask);}publicCriteriaanySet(List<Integer> positions){returnthis.positions("$bitsAnySet", positions);}privateCriteriapositions(String operator,List<Integer> positions){Assert.notNull(positions,"Positions must not be null!");Assert.noNullElements(positions.toArray(),"Positions must not contain null values.");this.target.criteria.put(operator, positions);returnthis.target;}privateCriteriastringBitmask(String operator,String bitmask){Assert.hasText(bitmask,"Bitmask must not be null!");this.target.criteria.put(operator,newBinary(Base64Utils.decodeFromString(bitmask)));returnthis.target;}privateCriterianumericBitmask(String operator,int bitmask){this.target.criteria.put(operator, bitmask);returnthis.target;}}publicinterfaceBitwiseCriteriaOperators{CriteriaallClear(int var1);CriteriaallClear(String var1);CriteriaallClear(List<Integer> var1);CriteriaallSet(int var1);CriteriaallSet(String var1);CriteriaallSet(List<Integer> var1);CriteriaanyClear(int var1);CriteriaanyClear(String var1);CriteriaanyClear(List<Integer> var1);CriteriaanySet(int var1);CriteriaanySet(String var1);CriteriaanySet(List<Integer> var1);}}}

3、MongoTemplate结合BasicQueryBasicQuery是Query的子类

4、MongoTemplate结合Aggregation使用Aggregation聚合查询


本文转载自: https://blog.csdn.net/paulwang040/article/details/128922162
版权归原作者 菠菜很好吃 所有, 如有侵权,请联系我们删除。

“java操作mongodb源码”的评论:

还没有评论