MongoDB模糊查询java实现样例

来源:互联网 发布:装修网络推广 编辑:程序博客网 时间:2024/05/22 12:38

在我的mongoDB中北京共有16个区县

这里写图片描述


其中只有密云和延庆是县,其他的为区,现在要将这两个例外查出来


直接用mongoDB shell命令是这样查询的:

db.country.find({'name':{$regex:/县/},'sheng':'11','level':3})

java实现如下:

package com.adtec.mongodb;import java.util.Iterator;import java.util.regex.Pattern;import com.mongodb.BasicDBObject;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBCursor;import com.mongodb.DBObject;import com.mongodb.MongoClient;/** *  * @author 浪丶荡  * <br> * 模糊查询实例 * */public class BlurQuery {    private String host = "192.168.71.193";    private int port = 27017;    public static void main(String[] args) {        BlurQuery blurQuery = new BlurQuery();        //数据库test        String dbname = "test";        DB db = blurQuery.getDB(dbname);        //集合country        String collectionName = "country";        //获取结果集        DBCursor cur = blurQuery.query(db, collectionName);        //show一下结果        blurQuery.printDBCursor(cur);    }    /**     *      * @param dbname     * @return 获取一个与指定数据库相关联的DB对象     */    public DB getDB(String dbname) {        @SuppressWarnings("resource")        MongoClient mongoClient = new MongoClient(host, port);        @SuppressWarnings("deprecation")        DB db = mongoClient.getDB(dbname);        return db;    }    /**     *      * @param db     * @param name     * @return DBCursor     * 查询北京市县级单位带"县"字的城市<br>     * mongodb vue 是db.country.find({'name':{$regex:/县/},'sheng':'11','level':3})     */    public DBCursor query(DB db, String collectionName) {        DBCollection dbColl = db.getCollection(collectionName);        // 模糊匹配正则规则(只要名字里带县字)        Pattern pattern = Pattern.compile("^.*县.*$", Pattern.CASE_INSENSITIVE);        BasicDBObject query = new BasicDBObject();        //加入查询条件        query.put("name", pattern);        query.put("sheng", "11");        query.put("level", 3);        //按名次升序排序        BasicDBObject sort = new BasicDBObject();        // 1,表示正序; -1,表示倒序        sort.put("name", 1);        DBCursor cur = dbColl.find(query).sort(sort);        return cur;    }    /**     *  遍历结果集     * @param cur     */    private void printDBCursor(DBCursor cur) {        Iterator<DBObject> iterator = cur.iterator();        while (iterator.hasNext()) {            System.out.println(iterator.next());        }    }}

结果:

十一月 21, 2017 3:12:16 下午 com.mongodb.diagnostics.logging.JULLogger log信息: Cluster created with settings {hosts=[192.168.71.193:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}十一月 21, 2017 3:12:16 下午 com.mongodb.diagnostics.logging.JULLogger log信息: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=192.168.71.193:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out十一月 21, 2017 3:12:16 下午 com.mongodb.diagnostics.logging.JULLogger log信息: Opened connection [connectionId{localValue:1, serverValue:14}] to 192.168.71.193:27017十一月 21, 2017 3:12:16 下午 com.mongodb.diagnostics.logging.JULLogger log信息: Monitor thread successfully connected to server with description ServerDescription{address=192.168.71.193:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 4, 5]}, minWireVersion=0, maxWireVersion=5, maxDocumentSize=16777216, roundTripTimeNanos=1732855}十一月 21, 2017 3:12:16 下午 com.mongodb.diagnostics.logging.JULLogger log信息: Opened connection [connectionId{localValue:2, serverValue:15}] to 192.168.71.193:27017{ "_id" : { "$oid" : "59ec563f937ceb812c804c65"} , "code" : "110228" , "sheng" : "11" , "di" : "02" , "xian" : "28" , "name" : "密云县" , "level" : 3.0}{ "_id" : { "$oid" : "59ec563f937ceb812c804c66"} , "code" : "110229" , "sheng" : "11" , "di" : "02" , "xian" : "29" , "name" : "延庆县" , "level" : 3.0}
原创粉丝点击