好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java操作mongodb的模糊查询和精确查询

本意是想查查mongo数据库的int类型的like怎么查,但是好像没 解决这个问题。

精确查询;模糊查询;分页查询,每页多少:按某个字段排序(或升或降):查询数量:大于,小于,等于;且,或,某个字段不为空,某个字段不存在,查询在某个范围内,删除等等查询。

一. 常用查询:

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

?

1

2

3

public PageUrl getByUrl(String url) {

   return findOne( new Query(Criteria.where( "url" ).is(url)),PageUrl. class );

  }

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

?

1

2

3

4

5

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 );  

  }

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

?

1

2

3

4

5

6

7

8

9

10

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 );

  }

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

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

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 );

  }

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

?

1

2

3

4

5

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 );

  }

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

?

1

Criteria.where( "key1" ).ne( "" ).ne( null )

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

?

1

2

Criteria criteria = new Criteria();

criteria.orOperator(Criteria.where( "key1" ).is( "0" ),Criteria.where( "key1" ).is( null ));

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

?

1

2

3

4

5

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 );

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

?

1

2

3

4

5

6

7

8

9

var s = {

   key1: value1,

   key2: {

    keyA: valueA,

    keyB: valueB

   }

  };

@Query ( "{'key2.keyA':?0}" )

List<Asset> findAllBykeyA(String keyA);

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

?

1

2

3

4

5

6

7

8

9

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 );

  }

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

?

1

2

3

4

5

6

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 );

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

?

1

2

3

4

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 );

  }

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

//调用更新

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 );

  }

8. 删除数据:

?

1

2

3

public void deleteObject(Class<T> clazz,String id) {

   remove( new Query(Criteria.where( "id" ).is(id)),clazz);

  }

9.保存数据:

?

1

2

3

4

5

6

7

8

9

10

//插入一条数据

public void saveObject(Object obj) {

   insert(obj);

  }

//插入多条数据 

public void saveObjects(List<T> objects) {

   for (T t:objects){

    insert(t);

   }

  }

我自己使用的例子:

下面例子涉及到:

精确查询:is;

模糊查询:regex;

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

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

查询数量:count

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

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;

}

mongo数据库里面像搜索数据类型为int的字段,

然后想使用like语句来着,但是没有实现,

因为我的port端口存的事int属性,

但是在列表页面,要支持字段搜索的话,然后我的int类型的端口字段,就不支持搜索了,

然后就考虑,既然是端口,那就是一个固定的,唯一的,

为什么要支持like语句呢?

你搜索端口号是1的就搜出来的是1的端口号就对了,而不是1,11,21,,,等等都个搜索出来,

所以,

对去其他的字符串 类型的字段,你使用like语句搜索,

我是没意见的,

要是非得 实现int类型的like搜索,

我 也不知道啊。

只有改数据结构,

让int型变成string型的话,

就可以like搜索啦。

原文链接:http://blog.csdn.net/qq_27093465/article/details/51578369

查看更多关于Java操作mongodb的模糊查询和精确查询的详细内容...

  阅读:54次