mongo java 工具类,mongodb Java 工具类

package com.mongodb;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import org.bson.Document;

import org.bson.conversions.Bson;

import org.bson.types.ObjectId;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import com.mongodb.BasicDBObject;

import com.mongodb.MongoClient;

import com.mongodb.MongoClientOptions;

import com.mongodb.MongoClientOptions.Builder;

import com.mongodb.WriteConcern;

import com.mongodb.client.MongoCollection;

import com.mongodb.client.MongoCursor;

import com.mongodb.client.MongoDatabase;

import com.mongodb.client.MongoIterable;

import com.mongodb.client.model.Filters;

import com.mongodb.client.result.DeleteResult;

/**

*

* 备注:mongodb 链接工具类 作者:qinxuewu 时间:2015年8月15日下午6:02:09

*/

public class MongoDBUtil {

private static MongoClient mongoClient;

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

static {

logger.info("===============MongoDBUtil初始化========================");

mongoClient = new MongoClient("localhost", 27017);

// 大部分用户使用mongodb都在安全内网下,但如果将mongodb设为安全验证模式,就需要在客户端提供用户名和密码:

// boolean auth = db.authenticate(myUserName, myPassword);

Builder options = new MongoClientOptions.Builder();

// options.autoConnectRetry(true);// 自动重连true

// options.maxAutoConnectRetryTime(10); // the maximum auto connect

// retry time

options.connectionsPerHost(300);// 连接池设置为300个连接,默认为100

options.connectTimeout(15000);// 连接超时,推荐>3000毫秒

options.maxWaitTime(5000); //

options.socketTimeout(0);// 套接字超时时间,0无限制

// 线程队列数,如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。

options.threadsAllowedToBlockForConnectionMultiplier(5000);

options.writeConcern(WriteConcern.SAFE);

options.build();

}

/**

* 获取DB实例 - 指定DB

*

* @param dbName

* @return

*/

public static MongoDatabase getDB(String dbName) {

if (dbName != null && !"".equals(dbName)) {

MongoDatabase database = mongoClient.getDatabase(dbName);

return database;

}

return null;

}

/**

* 获取collection对象 - 指定Collection

*

* @param collName

* @return

*/

public static MongoCollection getCollection(String dbName,

String collName) {

if (null == collName || "".equals(collName)) {

return null;

}

if (null == dbName || "".equals(dbName)) {

return null;

}

MongoCollection collection = mongoClient.getDatabase(dbName).getCollection(collName);

return collection;

}

/**

* 查询DB下的所有表名

*/

public static List getAllCollections(String dbName) {

MongoIterable colls = getDB(dbName).listCollectionNames();

List _list = new ArrayList();

for (String s : colls) {

_list.add(s);

}

return _list;

}

/**

* 获取所有数据库名称列表

*

* @return

*/

public static MongoIterable getAllDBNames() {

MongoIterable s = mongoClient.listDatabaseNames();

return s;

}

/**

* 删除一个数据库

*/

public static void dropDB(String dbName) {

getDB(dbName).drop();

}

/***

* 删除文档

*

* @param dbName

* @param collName

*/

public static void dropCollection(String dbName, String collName) {

getDB(dbName).getCollection(collName).drop();

}

/**

* 查找对象 - 根据主键_id

*

* @param collection

* @param id

* @return

*/

public static Document findById(MongoCollection coll, String id) {

try {

ObjectId _id = null;

try {

_id = new ObjectId(id);

} catch (Exception e) {

return null;

}

Document myDoc = coll.find(Filters.eq("_id", _id)).first();

return myDoc;

} catch (Exception e) {

e.printStackTrace();

close();

}

return null;

}

/***

* 条件查询对象

* @param coll

* @param filter

* @return

*/

public static Document findByNames(MongoCollection coll, Bson filter) {

try {

return coll.find(filter).first();

} catch (Exception e) {

e.printStackTrace();

close();

}

return null;

}

/***

* 多条件查询对象

* @param coll

* @param filter

* @return

*/

public static Document findByNames(MongoCollection coll,Map map) {

try {

return coll.find(new BasicDBObject(map)).first();

} catch (Exception e) {

e.printStackTrace();

close();

}

return null;

}

/** 统计数 */

public static int getCount(MongoCollection coll) {

try {

int count = (int) coll.count();

return count;

} catch (Exception e) {

e.printStackTrace();

close();

}

return 0;

}

/** 查询 多个集合文档*/

public static MongoCursor find(MongoCollection coll, Bson filter) {

try {

return coll.find(filter).iterator();

} catch (Exception e) {

e.printStackTrace();

close();

}

return null;

}

/**

* map集合 多条件查询

* @param coll

* @param map

* @return

*/

public static MongoCursor find(MongoCollection coll, Map map) {

try {

return coll.find(new BasicDBObject(map)).iterator();

} catch (Exception e) {

e.printStackTrace();

close();

}

return null;

}

/***

* 分页查询 默认按_id字段降序

* @param coll

* @param map

* @param pageNo

* @param pageSize

* @return

*/

public static MongoCursor findByPage(MongoCollection coll, Map map, int pageNo, int pageSize){

try {

Bson orderBy = new BasicDBObject("_id", -1);

return coll.find(new BasicDBObject(map)).sort(orderBy).skip((pageNo - 1) * pageSize).limit(pageSize).iterator();

} catch (Exception e) {

e.printStackTrace();

close();

}

return null;

}

/**

* 分页查询 自定义排序

* @param coll

* @param sorting

* @param name

* @param map

* @param pageNo

* @param pageSize

* @return

*/

public static MongoCursor findByPage(MongoCollection coll,String sorting,String name,

Map map, int pageNo, int pageSize){

try {

Bson orderBy=null;

//降序

if(sorting.equals("desc")){

orderBy= new BasicDBObject(name, -1);

}else{

orderBy= new BasicDBObject(name, 1);

}

return coll.find(new BasicDBObject(map)).sort(orderBy).skip((pageNo - 1) * pageSize).limit(pageSize).iterator();

} catch (Exception e) {

e.printStackTrace();

close();

}

return null;

}

/**

* 通过ID删除

*

* @param coll

* @param id

* @return

*/

public static int deleteById(MongoCollection coll, String id) {

try {

int count = 0;

ObjectId _id = null;

_id = new ObjectId(id);

Bson filter = Filters.eq("_id", _id);

DeleteResult deleteResult = coll.deleteOne(filter);

count = (int) deleteResult.getDeletedCount();

return count;

} catch (Exception e) {

e.printStackTrace();

close();

}

return 0;

}

/**

* 修改

*

* @param coll

* @param id

* @param newdoc

* @return

*/

public static Document updateById(MongoCollection coll, String id, Document newdoc) {

ObjectId _idobj = null;

try {

_idobj = new ObjectId(id);

Bson filter = Filters.eq("_id", _idobj);

// coll.replaceOne(filter, newdoc); // 完全替代

coll.updateOne(filter, new Document("$set", newdoc));

return newdoc;

} catch (Exception e) {

e.printStackTrace();

close();

}

return null;

}

/**

* 添加

* @param coll

* @param doc

* @return

*/

public static boolean save(MongoCollection coll,Document doc){

boolean falg=false;

try {

coll.insertOne(doc);

falg=true;

} catch (Exception e) {

e.printStackTrace();

logger.error("添加异常,异常信息:", e);

}finally{

close();

}

return falg;

}

/**

* 关闭Mongodb

*/

public static void close() {

if (mongoClient != null) {

mongoClient.close();

mongoClient = null;

}

}

public static void main(String[] args) {

MongoCollection list = getCollection("mydb", "users");

Document d = list.find().first();

System.out.println("userid====" + d.get("userid"));

System.out.println(d);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值