Home Java javaTutorial Sharing various examples of mongodb operation query in Java

Sharing various examples of mongodb operation query in Java

Sep 25, 2017 am 10:38 AM
java mongodb

这篇文章主要介绍了java 中mongodb的各种操作查询的实例详解的相关资料,希望通过本文能帮助到大家,需要的朋友可以参考下

java 中mongodb的各种操作查询的实例详解

一. 常用查询:

1. 查询一条数据:(多用于保存时判断db中是否已有当前数据,这里 is  精确匹配,模糊匹配 使用regex...)


  public PageUrl getByUrl(String url) { 
      return findOne(new Query(Criteria.where("url").is(url)),PageUrl.class); 
    }
Copy after login

2. 查询多条数据:linkUrl.id 属于分级查询


  public List<PageUrl> getPageUrlsByUrl(int begin, int end,String linkUrlid) {     
      Query query = new Query(); 
      query.addCriteria(Criteria.where("linkUrl.id").is(linkUrlid)); 
      return find(query.limit(end - begin).skip(begin), PageUrl.class);     
    }
Copy after login

3.模糊查询:-----关键字---regex


 public long getProcessLandLogsCount(List<Condition> conditions) 
    { 
      Query query = new Query(); 
      if (conditions != null && conditions.size() > 0) { 
        for (Condition condition : conditions) { 
          query.addCriteria(Criteria.where(condition.getKey()).regex(".*?\\" +condition.getValue().toString()+ ".*")); 
        } 
      } 
      return count(query, ProcessLandLog.class); 
    }
Copy after login

最下面,我在代码亲自实践过的模糊查询,只支持字段属性是字符串的查询,你要是查字段属性是int的模糊查询,还真没辙。

4.gte: 大于等于,lte小于等于...注意查询的时候各个字段的类型要和mongodb中数据类型一致


 public List<ProcessLandLog> getProcessLandLogs(int begin,int end,List<Condition> conditions,String orderField,Direction direction) 
    { 
      Query query = new Query(); 
      if (conditions != null && conditions.size() > 0) { 
        for (Condition condition : conditions) { 
          if(condition.getKey().equals("time")){ 
            query.addCriteria(Criteria.where("time").gte(condition.getValue())); //gte: 大于等于 
          }else if(condition.getKey().equals("insertTime")){ 
            query.addCriteria(Criteria.where("insertTime").gte(condition.getValue())); 
          }else{ 
            query.addCriteria(Criteria.where(condition.getKey()).is(condition.getValue())); 
          } 
        } 
      } 
      return find(query.limit(end - begin).skip(begin).with(new Sort(new Sort.Order(direction, orderField))), ProcessLandLog.class); 
    } 
   
  public List<DpsLand> getDpsLandsByTime(int begin, int end, Date beginDate,Date endDate) { 
   return find(new Query(Criteria.where("updateTime").gte(beginDate).lte(endDate)).limit(end - begin).skip(begin), 
    DpsLand.class); 
   }
Copy after login

查询字段不存在的数据 -----关键字---not


public List<GoodsDetail> getGoodsDetails2(int begin, int end) { 
      Query query = new Query(); 
      query.addCriteria(Criteria.where("goodsSummary").not()); 
      return find(query.limit(end - begin).skip(begin),GoodsDetail.class); 
    }
Copy after login

查询字段不为空的数据 -----关键字---ne


  Criteria.where("key1").ne("").ne(null)
Copy after login

查询或语句:a || b ----- 关键字---orOperator


 Criteria criteria = new Criteria(); 
  criteria.orOperator(Criteria.where("key1").is("0"),Criteria.where("key1").is(null));
Copy after login

查询且语句:a && b ----- 关键字---and


  Criteria criteria = new Criteria(); 
  criteria.and("key1").is(false); 
  criteria.and("key2").is(type); 
  Query query = new Query(criteria); 
  long totalCount = this.mongoTemplate.count(query, Xxx.class);
Copy after login

查询一个属性的子属性,例如:查下面数据的key2.keyA的语句


  var s = { 
      key1: value1, 
      key2: { 
        keyA: valueA, 
        keyB: valueB 
      } 
    }; 
   
  @Query("{&#39;key2.keyA&#39;:?0}") 
  List<Asset> findAllBykeyA(String keyA);
Copy after login

5. 查询数量:----- 关键字---count


 public long getPageInfosCount(List<Condition> conditions) { 
      Query query = new Query(); 
      if (conditions != null && conditions.size() > 0) { 
        for (Condition condition : conditions) { 
          query.addCriteria(Criteria.where(condition.getKey()).is(condition.getValue())); 
        } 
      } 
      return count(query, PageInfo.class); 
    }
Copy after login

查找包含在某个集合范围:----- 关键字---in


  Criteria criteria = new Criteria(); 
  Object [] o = new Object[]{0, 1, 2}; //包含所有 
  criteria.and("type").in(o); 
  Query query = new Query(criteria); 
  query.with(new Sort(new Sort.Order(Direction.ASC, "type"))).with(new Sort(new Sort.Order(Direction.ASC, "title"))); 
  List<WidgetMonitor> list = this.mongoTemplate.find(query, WidgetMonitor.class);
Copy after login

6. 更新一条数据的一个字段:


  public WriteResult updateTime(PageUrl pageUrl) { 
      String id = pageUrl.getId(); 
      return updateFirst(new Query(Criteria.where("id").is(id)),Update.update("updateTime", pageUrl.getUpdateTime()), PageUrl.class); 
    }
Copy after login

7. 更新一条数据的多个字段:


  //调用更新 
  private void updateProcessLandLog(ProcessLandLog processLandLog, 
        int crawlResult) { 
      List<String> fields = new ArrayList<String>(); 
      List<Object> values = new ArrayList<Object>(); 
      fields.add("state"); 
      fields.add("result"); 
      fields.add("time"); 
      values.add("1"); 
      values.add(crawlResult); 
      values.add(Calendar.getInstance().getTime()); 
      processLandLogReposity.updateProcessLandLog(processLandLog, fields, 
          values); 
    } 
  //更新 
  public void updateProcessLandLog(ProcessLandLog land, List<String> fields,List<Object> values) { 
      Update update = new Update(); 
      int size = fields.size(); 
      for(int i = 0 ; i < size; i++){ 
        String field = fields.get(i); 
        Object value = values.get(i); 
        update.set(field, value); 
      } 
      updateFirst(new Query(Criteria.where("id").is(land.getId())), update,ProcessLandLog.class); 
    }
Copy after login

8. 删除数据:


  public void deleteObject(Class<T> clazz,String id) { 
      remove(new Query(Criteria.where("id").is(id)),clazz); 
    }
Copy after login

9.保存数据:


//插入一条数据 
  public void saveObject(Object obj) { 
      insert(obj); 
    } 
   
  //插入多条数据   
  public void saveObjects(List<T> objects) { 
      for(T t:objects){ 
        insert(t); 
      } 
    }
Copy after login

我自己使用的例子:

下面例子涉及到:

精确查询:is;

模糊查询:regex;

分页查询,每页多少:skip,limit

按某个字段排序(或升或降):new Sort(new Sort.Order(Sort.Direction.ASC, "port"))

查询数量:count


  public Map<String, Object> getAppPortDetailByPage(int pageNo, int pageSize, String order, String sortBy, String appPortType, String appPortSeacherName) { 
    Criteria criteria = new Criteria(); 
    if (!appPortType.equals("")) { 
      if (!appPortType.equals("all")) { 
        //DB表里的字段----appmanageType 
        //下同 port protocol 也是DB表的字段 
        criteria.and("appmanageType").is(appPortType); 
      } 
    } 
    if (!appPortSeacherName.equals("")) { 
      try { 
        criteria.orOperator(Criteria.where("port").is(Integer.parseInt(appPortSeacherName)), 
            Criteria.where("protocol").regex(".*?" + appPortSeacherName + ".*")); 
      }catch (Exception e){ 
        criteria.orOperator(Criteria.where("protocol").regex(".*?" + appPortSeacherName + ".*")); 
      } 
    } 
    Map<String, Object> result = Maps.newHashMap(); 
    Query query = new Query(criteria); 
    query.skip((pageNo - 1) * pageSize); 
    query.limit(pageSize); 
    if(order != null && sortBy != null){ 
      query.with(new Sort(new Sort.Order(order.equals("asc") ? Sort.Direction.ASC : Sort.Direction.DESC, sortBy))); 
    }else { 
      query.with(new Sort(new Sort.Order(Sort.Direction.ASC, "port"))); 
    } 
    List<Appportmanage> list = this.mongoTemplate.find(query, Appportmanage.class); 
    long count = this.mongoTemplate.count(query, Appportmanage.class); 
    result.put("datas", list); 
    result.put("size", count); 
    return result; 
  }
Copy after login

The above is the detailed content of Sharing various examples of mongodb operation query in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Apr 18, 2025 am 11:48 AM

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

What is the CentOS MongoDB backup strategy? What is the CentOS MongoDB backup strategy? Apr 14, 2025 pm 04:51 PM

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

See all articles