欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java操作mongodb(高级查询)

程序员文章站 2022-05-08 16:50:19
...

转自:https://blog.csdn.net/maosijunzi/article/details/42100535

直接上代码(依赖代码请查看之前的博客):

public void query() {
		// $or (查询id等于1或者id等于2的数据)
		BasicDBObject queryObject = new BasicDBObject().append(
				QueryOperators.OR,
				new BasicDBObject[] { new BasicDBObject("id", 1),
						new BasicDBObject("id", 2) });
		find(queryObject, "(查询id等于1或者id等于2的数据)");
	// $and(查询id等于10并且name等于10的数据)
	queryObject = new BasicDBObject().append(QueryOperators.AND,
			new BasicDBObject[] { new BasicDBObject("id", 10),
					new BasicDBObject("name", "10") });
	find(queryObject, "(查询id等于10并且name等于10的数据)");

	// $gt(查询id大于10的数据)
	queryObject = new BasicDBObject().append("id",
			new BasicDBObject().append(QueryOperators.GT, 10));
	find(queryObject, "(查询id大于10的数据)");
	// $gte (查询id大于等于10的数据)
	queryObject = new BasicDBObject().append("id",
			new BasicDBObject().append(QueryOperators.GTE, 11));
	find(queryObject, "(查询id大于等于11的数据)");
	// $lt
	queryObject = new BasicDBObject().append("id",
			new BasicDBObject().append(QueryOperators.LT, 2));
	find(queryObject, "(查询id小于2的数据)");
	// $lte
	queryObject = new BasicDBObject().append("id",
			new BasicDBObject().append(QueryOperators.LTE, 2));
	find(queryObject, "(查询id小于等于2的数据)");

	// $in
	queryObject = new BasicDBObject().append("id", new BasicDBObject(
			QueryOperators.IN, new int[] { 1, 2 }));
	find(queryObject, "(查询id为1和2的数据)");
	// $nin
	queryObject = new BasicDBObject().append("id", new BasicDBObject(
			QueryOperators.NIN, new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }));
	find(queryObject, "(查询id不为1,2,3,4,5,6,7,8,9的数据)");

	// 还有很多其他的高级查询方式可以参见QueryOperators类
}

public void find(BasicDBObject condition, String str) {
	System.out.println("================" + str + "==================");
	DB db = MongoManager.getDB(Constants.DB);
	DBCollection collection = db.getCollection(Constants.COLLECTION_USER);
	DBCursor find = collection.find(condition);
	while (find.hasNext()) {
		User user = new User();
		user.parse(find.next());
		System.out.println(user);
	}

}

public static void main(String[] args) {
	UserDao userDao = new UserDao();
	userDao.query();
}</code></pre>


QueryOperators类源码:

// QueryOperators.java

/**

  •  Copyright (C) 2010 10gen Inc.
    
  • Licensed under the Apache License, Version 2.0 (the “License”);
  • you may not use this file except in compliance with the License.
  • You may obtain a copy of the License at
  •  http://www.apache.org/licenses/LICENSE-2.0
    
  • Unless required by applicable law or agreed to in writing, software
  • distributed under the License is distributed on an “AS IS” BASIS,
  • WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  • See the License for the specific language governing permissions and
  • limitations under the License.
    */
    package com.mongodb;

/**

  • MongoDB keywords for various query operations

  • @author Julson Lim
    */
    public class QueryOperators {
    public static final String OR = “or&quot;;publicstaticfinalStringAND=&quot;or&quot;; public static final String AND = &quot;and”;

    public static final String GT = “gt&quot;;publicstaticfinalStringGTE=&quot;gt&quot;; public static final String GTE = &quot;gte”;
    public static final String LT = “lt&quot;;publicstaticfinalStringLTE=&quot;lt&quot;; public static final String LTE = &quot;lte”;

    public static final String NE = “ne&quot;;publicstaticfinalStringIN=&quot;ne&quot;; public static final String IN = &quot;in”;
    public static final String NIN = “nin&quot;;publicstaticfinalStringMOD=&quot;nin&quot;; public static final String MOD = &quot;mod”;
    public static final String ALL = “all&quot;;publicstaticfinalStringSIZE=&quot;all&quot;; public static final String SIZE = &quot;size”;
    public static final String EXISTS = “exists&quot;;publicstaticfinalStringELEMMATCH=&quot;exists&quot;; public static final String ELEM_MATCH = &quot;elemMatch”;

    // (to be implemented in QueryBuilder)
    public static final String WHERE = “where&quot;;publicstaticfinalStringNOR=&quot;where&quot;; public static final String NOR = &quot;nor”;
    public static final String TYPE = “type&quot;;publicstaticfinalStringNOT=&quot;type&quot;; public static final String NOT = &quot;not”;

    // geo operators
    public static final String WITHIN = “within&quot;;publicstaticfinalStringNEAR=&quot;within&quot;; public static final String NEAR = &quot;near”;
    public static final String NEAR_SPHERE = “nearSphere&quot;;publicstaticfinalStringBOX=&quot;nearSphere&quot;; public static final String BOX = &quot;box”;
    public static final String CENTER = “center&quot;;publicstaticfinalStringPOLYGON=&quot;center&quot;; public static final String POLYGON = &quot;polygon”;
    public static final String CENTER_SPHERE = “centerSphere&quot;;//(tobeimplementedinQueryBuilder)publicstaticfinalStringMAXDISTANCE=&quot;centerSphere&quot;; // (to be implemented in QueryBuilder) public static final String MAX_DISTANCE = &quot;maxDistance”;
    public static final String UNIQUE_DOCS = “$uniqueDocs”;

    // meta query operators (to be implemented in QueryBuilder)
    public static final String RETURN_KEY = “returnKey&quot;;publicstaticfinalStringMAXSCAN=&quot;returnKey&quot;; public static final String MAX_SCAN = &quot;maxScan”;
    public static final String ORDER_BY = “orderby&quot;;publicstaticfinalStringEXPLAIN=&quot;orderby&quot;; public static final String EXPLAIN = &quot;explain”;
    public static final String SNAPSHOT = “snapshot&quot;;publicstaticfinalStringMIN=&quot;snapshot&quot;; public static final String MIN = &quot;min”;
    public static final String MAX = “max&quot;;publicstaticfinalStringSHOWDISKLOC=&quot;max&quot;; public static final String SHOW_DISK_LOC = &quot;showDiskLoc”;
    public static final String HINT = “hint&quot;;publicstaticfinalStringCOMMENT=&quot;hint&quot;; public static final String COMMENT = &quot;comment”;
    }


 

输出结果:

================(查询id等于1或者id等于2的数据)==================
id:1,name:jinhui,address:beijing
id:2,name:manman,address:beijing
================(查询id等于10并且name等于10的数据)==================
================(查询id大于10的数据)==================
id:11,name:11,address:11
id:12,name:12,address:12
================(查询id大于等于11的数据)==================
id:11,name:11,address:11
id:12,name:12,address:12
================(查询id小于2的数据)==================
id:1,name:jinhui,address:beijing
================(查询id小于等于2的数据)==================
id:1,name:jinhui,address:beijing
id:2,name:manman,address:beijing
================(查询id为1和2的数据)==================
id:1,name:jinhui,address:beijing
id:2,name:manman,address:beijing
================(查询id不为1,2,3,4,5,6,7,8,9的数据)==================
id:11,name:11,address:11
id:12,name:12,address:12

数据库数据如下所示:

java操作mongodb(高级查询)