根据 使用 mongodb,总结了一些简单的操作方法。希望帮助大家。
1.连接 mongodb://根据用户名,密码进行连接 mongodb 数据库
public class MongoManager{
private static MongoDatabase mongoDatabase = null;
private final static Logger LOGGER = LoggerFactory.getLogger(MongoManager.class);
private MongoManager(){}
/**
* 获取数据库链接
* @return Connection
*/
public static MongoDatabase getMongoDataBase(){
if (mongoDatabase != null) {
return mongoDatabase; //如果已经有连接,直接返回,不重新连接!
}
try {
InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("mongo.properties"); //通过配置文件,设置mongodb 连接的参数。获取当前线程的配置文件!!!
Properties properties = new Properties();
properties.load(inStream);
String host = properties.getProperty("mongo.host");
int port = Integer.valueOf(properties.getProperty("mongo.port"));
String userName = properties.getProperty("mongo.username");
char[] password = properties.getProperty("mongo.password").toCharArray();
String database = properties.getProperty("mongo.database");
//连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
//ServerAddress()两个参数分别为 服务器地址 和 端口
ServerAddress serverAddress = new ServerAddress(host, port);
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
//MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
MongoCredential credential = MongoCredential.createScramSha1Credential(userName, database, password);
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
//
MongoClientOptions.Builder build = new MongoClientOptions.Builder();
//与目标数据库能够建立的最大connection数量为50
build.connectionsPerHost(50);
//如果当前所有的connection都在使用中,则每个connection上可以有50个线程排队等待
build.threadsAllowedToBlockForConnectionMultiplier(50);
/*
* 一个线程访问数据库的时候,在成功获取到一个可用数据库连接之前的最长等待时间为2分钟
* 这里比较危险,如果超过maxWaitTime都没有获取到这个连接的话,该线程就会抛出Exception
* 故这里设置的maxWaitTime应该足够大,以免由于排队线程过多造成的数据库访问失败
*/
build.maxWaitTime(1000*60*2);
build.connectTimeout(1000*60*1); //与数据库建立连接的timeout设置为1分钟
MongoClientOptions mongoClientOptions = build.build();
//通过连接认证获取MongoDB连接
MongoClient mongoClient = new MongoClient(addrs,credentials,mongoClientOptions);
//连接到数据库
mongoDatabase = mongoClient.getDatabase(database);
System.out.println("Connect to mongoDB database successfully");
} catch (Exception e) {
LOGGER.error("连接到数据库失败",e);
}
return mongoDatabase;
}
/**
* 关闭资源
* @param mongoDatabase
* @param mongoClient
*/
public static void closeConnection(MongoDatabase mongoDatabase, MongoClient mongoClient){
try {
if (mongoDatabase != null) {
mongoDatabase = null;
}
if (mongoClient != null) {
mongoClient.close();
//然系统不会回收,只是关闭了,连接存在。
mongoClient = null;
}
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
}
public static void main( String args[] ){
try{
// 连接到数据库
getMongoDataBase();
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
2. 通过 java 操作 mongodb://部分常见的操作,设置为公共方法调用
public class MongoDAO {
private final static Logger LOGGER = LoggerFactory.getLogger(MongoDAO.class);
private static MongoDatabase mongoDatabase = MongoManager.getMongoDataBase();
private static Map<String,MongoCollection<Document>> collectionMap = new ConcurrentHashMap<>();
private MongoDAO() {
}
//获取 mongodb 连接
private static MongoCollection<Document> getCollection(String table){
if(!collectionMap.containsKey(table)){
MongoCollection<Document> mongoCollection = mongoDatabase
.getCollection(table);
collectionMap.put(table, mongoCollection);
}
return collectionMap.get(table);
}
/**
* 插入文档(数据记录行)
*
* @param table
* 数据库表名
* @param document
* 数据记录行/文档
* @return
*/
public static String insert(String table, Document document) {
try {
getCollection(table).insertOne(document);
Object id = document.get("_id");
return id != null ? id.toString() : null;
} catch (Exception e) {
String error = "插入数据失败!";
LOGGER.error(error, e);
}
return null;
}
/**
* 查询文档
*
* @param table
* 数据库表名
* @return
*/
public static MongoCursor<Document> getCollevtion(String table) {
try {
MongoCollection<Document> mongoCollection = getCollection(table);
FindIterable<Document> findIterable = mongoCollection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
// while(mongoCursor.hasNext()){
// System.out.println(mongoCursor.next());
// }
MongoManager.closeConnection(mongoDatabase, null);
return mongoCursor;
} catch (Exception e) {
LOGGER.error("查询文档失败");
}
return null;
}
/**
* 更新文档
*
* @param table
* 数据库表名
* @param fieldName
* 根据某个字段update,字段名称
* @param value
* 根据某个字段update,字段的值
* @param document
* @return
*/
public static UpdateResult update(String table, String fieldName, Object value,
Document document) {
try {
MongoCollection<Document> mongoCollection = getCollection(table);
UpdateResult result = mongoCollection.updateOne(
Filters.eq(fieldName, value), document);
return result;
} catch (Exception e) {
LOGGER.error("更新失败", e);
}
return null;
}
/**
* 查询文档
*
* @param table
* 数据库表名
* @return
*/
public static FindIterable<Document> find(String table) {
try {
MongoCollection<Document> mongoCollection = getCollection(table);
FindIterable<Document> findIterable = mongoCollection.find();
return findIterable;
} catch (Exception e) {
LOGGER.error("查询失败", e);
}
return null;
}
/**
* 根据某个数据字段名称和值查询
*
* @param table
* 数据库表名
* @param fieldName
* 根据字段查询,字段的名称
* @param value
* 根据字段查询,字段的值
* @return
*/
public static MongoCursor<Document> findByFiled(String table, String fieldName,
Object value) {
try {
MongoCollection<Document> mongoCollection = getCollection(table);
FindIterable<Document> findIterable = mongoCollection.find(Filters
.eq(fieldName, value));
MongoCursor<Document> mongoCursor = findIterable.iterator();
return mongoCursor;
} catch (Exception e) {
LOGGER.error("查询失败", e);
}
return null;
}
}
3. 通过 java 操作 mongodb --高级操作://根据条件查询
设置 mongodb 查询条件:
//设置 mongodb 查询条件
BasicDBObject basicDBObject = new BasicDBObject(); //查询条件集合
basicDBObject.put("**", companyId); // == 完全匹配
basicDBObject.put("**", 1);
basicDBObject.put("**", 1);
Map<String, Object> queryMapContent = new HashMap<>();
queryMapContent.put("$regex", "成功"); // 模糊查询,包含"$regex"
basicDBObject.put("content", new BasicDBObject(queryMapContent));
//时间作为查询条件
if (StringUtils.isNotEmpty(operateTimeStart) || StringUtils.isNotEmpty(operateTimeEnd)) {
Map<String, Object> queryMap = new HashMap<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
if (StringUtils.isNotEmpty(operateTimeStart)) {
Date start = sdf.parse(operateTimeStart);
queryMap.put("$gt", start); //起始时间,传过来时间格式如:yyyy.MM.dd HH:mm:ss
}
if (StringUtils.isNotEmpty(operateTimeEnd)) {
Date end = sdf.parse(operateTimeEnd);
queryMap.put("$lt", end); //结束时间
}
basicDBObject.put("createTime", new BasicDBObject(queryMap));
}
//对集合进行设置 ,存在在集合里面的值
if (CollectionUtils.isNotEmpty(departmentList)) {
Map<String, Object> queryMap = new HashMap<>();
queryMap.put("$in", departmentList);
basicDBObject.put("deptId", new BasicDBObject(queryMap));
}
if (StringUtils.isNotEmpty(queryName)) {
Map<String, Object> queryMap = new HashMap<>();
queryMap.put("$regex", queryName); //模糊查询,包含
basicDBObject.put("***", new BasicDBObject(queryMap));
}
if (StringUtils.isNotEmpty(queryUserName)) {
Map<String, Object> queryMap = new HashMap<>();
queryMap.put("$regex", queryUserName); // 模糊查询,包含
basicDBObject.put("***", new BasicDBObject(queryMap));
}
根据条件查询:
MongoDatabase mongoDataBase = MongoManager.getMongoDataBase(); //获取连接
MongoCollection<Document> collection = mongoDataBase.getCollection(LOG_COLLECTION_NAME);
FindIterable<Document> findIterable = collection.find(basicDBObject); //根据上面设置的查询条件进行查询。
findIterable = findIterable.sort(new BasicDBObject("createTime",sortNum));//排序 1 为升序排列,而 -1 是用于降序排列。
totalNum = Double.valueOf(collection.count(basicDBObject)); // count 查询结果有多少条数据
//
findIterable = findIterable.skip(skip).limit(limit); //skip 分页,从多少条开始取; limit 取多少条数据
MongoCursor<Document> mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
Document document = mongoCursor.next();
LogBean logBean = new LogBean();
int id = document.get("userId") != null ? Integer.parseInt(document.get("userId").toString()) : 0;
SimpleDateFormat sdfData= new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
try { //转换时间格式:mongodb 时间格式:"createTime" : ISODate("2018-06-11T03:27:21.695Z") ;需要时间格式:2018.07.03 17:02:29
String dateStr = document.get("createTime").toString();
Date date=sdfData.parse(dateStr);
logBean.setLastUpdateTime(date);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("",e);
}
}
1 为升序排列,而 -1 是用于降序排列。
totalNum = Double.valueOf(collection.count(basicDBObject)); // count 查询结果有多少条数据
//
findIterable = findIterable.skip(skip).limit(limit); //skip 分页,从多少条开始取; limit 取多少条数据
MongoCursor<Document> mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
Document document = mongoCursor.next();
LogBean logBean = new LogBean();
int id = document.get("userId") != null ? Integer.parseInt(document.get("userId").toString()) : 0;
SimpleDateFormat sdfData= new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
try { //转换时间格式:mongodb 时间格式:"createTime" : ISODate("2018-06-11T03:27:21.695Z") ;需要时间格式:2018.07.03 17:02:29
String dateStr = document.get("createTime").toString();
Date date=sdfData.parse(dateStr);
logBean.setLastUpdateTime(date);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("",e);
}
}
权限问题:(mongoDB用户权限,部署安装配置 & 命令行操作)
权限设置参考: https://www.cnblogs.com/xiaoqian1993/p/5944039.html
1. use admin
2.创建用户
3. 认证用户
遇见问题及解决方案
error:
> db.createUser({user:”root”,pwd:”root”,roles:[{role:"readWrite",db:”test”}]})
2018-04-24T09:34:03.610+0800 E QUERY [thread1] SyntaxError: illegal character @(shell):1:20
解决方法:修改特殊字符(自己变成那样的)
error:
使用用户名,密码连接mongodb。启动eclipse,过一会报错:
Timed out after 30000 ms while waiting to connect. Client view of cluster st....
解决方法:是用户权限没设置好,所以连接不成功!
操作 mongodb:
设置启动配置文件: 文件名称: /data/mongodb/conf/mongo.conf
bind_ip = 172.19.160.155
#端口号
port=21707
#数据库目录
dbpath=/data/mongodb/data
#日志目录
logpath=/data/mongodb/log/mongodb.log
logappend=true
# 是否以守护进程方式运行
fork = true
# 是否以安全认证方式运行,默认是不认证的非安全方式
#noauth = true
auth = true
mongodb /bin 下面启动文件: 文件名称 start.sh 启动方式 sh start.sh
#!/bin/bash
./mongod -f /data/mongodb/conf/mongo.conf
命令行登录:
[root@localhost bin]# mongo --host 172.19.160.155 --port 21707 //进入命令
>use admin //管理员权限,admin
> db.auth('admin','123456')
> use tc_trics // tc_trics库权限
> db.auth('worker','123456')
show collections