MongoDB查询

使用了jongo框架:

连接数据库:

数据库配置类:

 

package cn.com.rivercloud.common;

import com.mongodb.MongoClientOptions.Builder;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DbManager {
    private static volatile DbManager instance;

    private static final Logger logger = LoggerFactory.getLogger(DbManager.class);

    private MongoClient mongoClient;

    private DbManager() {

    }

    public static DbManager getInstance() {

        if (null == instance) {
            synchronized (DbManager.class) {
                if (null == instance) {
                    instance = new DbManager();
                    instance.init();
                }
            }
        }

        return instance;
    }

    private void init() {

        // 连接池选项
     
        // 选项构建者
        com.mongodb.MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        
        // 每个地址最大请求数
        builder.connectionsPerHost(8);
        builder.threadsAllowedToBlockForConnectionMultiplier(4);
        
        // 设置连接超时时间
        builder.connectTimeout(10000);
        
        // 设置最大等待时间
        builder.maxWaitTime(120000);
        
        // 读取数据的超时时间
        builder.socketTimeout(1500);

        MongoClientOptions options = builder.build();

        List<ServerAddress> hosts = new ArrayList<ServerAddress>();

        String host = "127.0.0.1";
        logger.info("dbhost:"+host);
        int port = 27017;
        hosts.add(new ServerAddress(host, port));
        List<MongoCredential> credentials = new ArrayList<MongoCredential>();
        mongoClient = new MongoClient(hosts);
       
    }

    public MongoClient getMongoClient() {
        return mongoClient;
    }
    
    public DB getDataDb() {
        DB db = mongoClient.getDB("data");
        return db;
    }
}

 

 

 

 

private static Jongo jongo;
static {
    DB db = DbManager.getInstance().getDataDb();
    jongo = new Jongo(db);
}

MongoCollection system_user = jongo.getCollection("system_user");

 

add:

User user = new User();
WriteResult result = system_user.insert(user);

 

delete:

WriteResult result = system_user.remove();

 

update:

byUsername为新的User实体。 
WriteResult with = system_user.update("{_id:#}", new ObjectId(id)).with(byUsername);

更改username为lisi的数据(包含多个)
system_user.update("{username:#}", "lisi")).multi().with(byUsername);


query:

普通查询:
MongoCursor<User> as = system_uesr.find().as(User.class);
MongoCursor<User> as = system_user.find().skip((pagination.getCurrent() - 1) * pagination.getPageSize()).limit(pagination.getPageSize()).as(User.class);
MongoCursor<User> as = system_uesr.find(“{username:#,password:#}”,‘lisi’,‘123’).as(User.class);

多条件符合查询:
用到
import org.springframework.data.mongodb.core.query.Criteria;
Criteria criteria = new Criteria();
String s = new Query(criteria).getQueryObject().toJson();

MongoCursor<Map> as = system_user.find(s).skip((pagination.getCurrent() - 1) * pagination.getPageSize()).limit(pagination.getPageSize()).as(Map.class);




---------------------------------------------------------------------------------------------------------------------------------------------------------------
多条件的另一种方法,不同的依赖,这个使用的是 org.mongodb 下的QueryBuilder;
QueryBuilder queryBuilder = QueryBuilder.start();
MongoCursor<Map> as = system_user.find(queryBuilder.get().toString()).skip((pagination.getCurrent() - 1) * pagination.getPageSize()).limit(pagination.getPageSize()).as(Map.class);

 Criteria的具体内容:

Criteria criteria = new Criteria();
//等于
criteria.where("url").is(“a12345”)

//模糊查询
criteria.where("url").regex(“a”);

//大于,小于等
criteria.where("age").lte(20);

//查询字段不存在的数据
criteria.where("url").not();

//查询字段不为空的数据
criteria.where("url").ne("").ne(null);

//查询或语句
criteria.orOperator(Criteria.where("key1").is("0"),Criteria.where("key1").is(null));  
//且语句
criteria.where("url").is(“a12345”).and("username").is("lisi");

//包含

  Object [] obj = new Object[]{0, 1, 2};   

  criteria.and("type").in(obj);  

 

QueryBuilder 的具体内容:
//查询匹配
queryBuilder.and(QueryBuilder.start("companyName").is("number1").get());

//模糊查询
Pattern pattern = Pattern.compile("@_");
queryBuilder.and(QueryBuilder.start("createId").regex(pattern).get());

//模糊查询
Pattern pattern = Pattern.compile("^.*"+name+".*$",Pattern.CASE_INSENSITIVE);
queryBuilder.or(queryBuilder.start("username").regex(pattern).get(),queryBuilder.start("accountName").regex(pattern).get());
//完全匹配
Pattern pattern = Pattern.compile("^王$", Pattern.CASE_INSENSITIVE);
//右匹配
Pattern pattern = Pattern.compile("^.*王$", Pattern.CASE_INSENSITIVE);
//左匹配
Pattern pattern = Pattern.compile("^王.*$", Pattern.CASE_INSENSITIVE);
//模糊匹配
Pattern pattern = Pattern.compile("^.*王.*$", Pattern.CASE_INSENSITIVE);

 

 

简单原生:

1、进入数据库

./mongo

2、选择数据库

use data

3、查询数据库表

show dbs

4、查询文档

db.user.find();

格式化:

db.user.find().pretty()

5、删除文档

db.user.remeve({})  //删除全部

db.user.remove({"id":"2"})  //按条件删除

posted @ 2020-05-13 18:33  忧伤还是快乐EL  阅读(241)  评论(0编辑  收藏  举报