进mongo

mongo

先添加admin表的账号密码

. use admin
.
db.createUser(
{
user: "admin",
pwd: "admin",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
. db.auth('admin','admin')
在admin登录情况下,切换到自己数据库操作 . use test
. db.createUser({user:'test',pwd:'test',roles:[{role:"dbOwner",db:"test"}]})
退出重新登录 . mongo
. use test
. db.auth('test','test')
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase; import org.bson.Document;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Repository; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; /**
* mongodb数据库操作
*
* @author Duan Yong
* @since 2016/11/11.
*/
@Repository
@SuppressWarnings("unchecked")
public class MongoDAO implements InitializingBean { private static Logger LOGGER = LoggerFactory.getLogger(MongoDAO.class);
private static MongoDatabase db; /**
* 根据名字获取数据库表
*/
public MongoCollection getCollection(String name) {
return db.getCollection(name);
} /**
* 返回文档list
*/
public List<Document> find(String collectionName, Document query, Document key, Document order, int skip,
int limit) {
MongoCollection collection = db.getCollection(collectionName);
List<Document> result = new ArrayList<>();
if (query == null) {
return result;
}
FindIterable<Document> iterable = collection.find(query);
if (order != null) {
iterable = iterable.sort(order);
}
if (skip > 0) {
iterable = iterable.skip(skip);
}
if (limit > 0) {
iterable = iterable.limit(limit);
}
if (key != null) {
iterable = iterable.projection(key);
}
iterable.into(result);
return result;
} /**
* 根据_id删除记录
*/
public void deleteById(String collectionName, String id) {
MongoCollection<Document> collection = db.getCollection(collectionName);
collection.deleteOne(new Document("_id", new ObjectId(id)));
} /**
* 根据查询条件删除记录
*/
public void delete(String collectionName, Document query) {
MongoCollection<Document> collection = db.getCollection(collectionName);
collection.deleteMany(query);
} /**
* 根据查询条件返回第一条
*
* @param collectionName,数据库名
* @param query,数据库表中记录id
*/
public Document findOne(String collectionName, Document query) {
MongoCollection<Document> collection = db.getCollection(collectionName);
return collection.find(query).first();
} /**
* 插入一条记录到数据库
*/
public void insert(String collectionName, Document document) {
MongoCollection collection = db.getCollection(collectionName);
collection.insertOne(document);
} /**
* 更新记录
*/
public void updateById(String collectionName, ObjectId id, Document document) {
MongoCollection collection = db.getCollection(collectionName);
collection.updateOne(new Document("_id",id), new Document("$set", document));
} @Override
public void afterPropertiesSet() throws Exception {
MongoClientOptions mongoClientOptions = new MongoClientOptions.Builder()
.connectionsPerHost(PropertiesUtil.getInt("mongoDB.option.activeConnectionCount", 10))
.connectTimeout(PropertiesUtil.getInt("mongoDB.option.connectTimeout"))
.socketTimeout(PropertiesUtil.getInt("mongoDB.option.socketTimeout"))
.maxWaitTime(PropertiesUtil.getInt("mongoDB.option.maxWaitTime"))
.threadsAllowedToBlockForConnectionMultiplier(
PropertiesUtil.getInt("mongoDB.option.threadsAllowedToBlockForConnectionMultiplier"))
.build();
String address = PropertiesUtil.get("mongoDB.address");
String database = PropertiesUtil.get("mongoDB.database");
String user = PropertiesUtil.get("mongoDB.user");
String pwd = PropertiesUtil.get("mongoDB.pwd");
try {
List<ServerAddress> serverAddresses = new ArrayList<>();
for (String add : address.split(" ")) {
serverAddresses.add(new ServerAddress(add));
}
MongoCredential credential = MongoCredential.createCredential(user, database, pwd.toCharArray());
MongoClient mongoClient = new MongoClient(serverAddresses, Arrays.asList(credential), mongoClientOptions);
db = mongoClient.getDatabase(database);
LOGGER.info("init mongoDao : " + address);
} catch (Exception e) {
LOGGER.error("init mongoDao error", e);
}
}
}

PS:propertisUtil自己写一个吧

mongo小记的更多相关文章

  1. MongoDB 小记

    之前本人说过一款非关系型数据库的代表 Redis 的 < Redis 小记 >文章,觉得意犹未尽,今天就来介绍一款数据库 MongoDB ,先来看一下 MongoDB是一款基于分布式文件存 ...

  2. 谈一谈NOSQL的应用,Redis/Mongo

    1.心路历程 上年11月份来公司了,和另外一个同事一起,做了公司一个移动项目的微信公众号,然后为了推广微信公众号,策划那边需要我们做一些活动,包括抽奖,投票.最开始是没有用过redis的,公司因为考虑 ...

  3. [原]Paste.deploy 与 WSGI, keystone 小记

    Paste.deploy 与 WSGI, keystone 小记 名词解释: Paste.deploy 是一个WSGI工具包,用于更方便的管理WSGI应用, 可以通过配置文件,将WSGI应用加载起来. ...

  4. MongoDB分组汇总操作,及Spring data mongo的实现

    转载请在页首注明作者与出处 一:分组汇总 1.1:SQL样例 分组汇总的应用场景非常多,比如查询每个班级的总分是多少,如果用关系形数据库,那么sql是这样子的 ),class from score g ...

  5. mongo DB for C#

    (1)Download the MongoDB C#驱动. http://www.nuget.org/packages/mongocsharpdriver/. (2) Add Reference to ...

  6. MySql 小记

    MySql  简单 小记 以备查看 1.sql概述 1.什么是sql? 2.sql发展过程? 3.sql标准与方言的关系? 4.常用数据库? 5.MySql数据库安装? 2.关键概念 表结构----- ...

  7. Mongo基础使用,以及在Express项目中使用Mongoose

    MongoDB的基本使用 MongoDB特点: 使用BSON存储数据 支持相对丰富的查询操作(相对其他nosql数据库) 支持索引 副本集(支持多个实例/多个服务器运行同个数据库) 分片(数据库水平扩 ...

  8. 【mongo】mongoVUE使用

    1.查询存在字段"test"的项 {"test":{$exists:true}} 2.在表中插入字段 {$set:{"}} 3.正则匹配 {" ...

  9. Git小记

    Git简~介 Git是一个分布式版本控制系统,其他的版本控制系统我只用过SVN,但用的时间不长.大家都知道,分布式的好处多多,而且分布式已经包含了集中式的几乎所有功能.Linus创造Git的传奇经历就 ...

随机推荐

  1. MaxScript镜像函数

    看到有网友需要写的,其实镜像就是缩放改为负数 Fn MirrorObject argObjects argAxisName = ( local axisNames = #(#x,#y,#z) do ( ...

  2. mysql--多表连接查询

    一.多表连接查询 SELECT 字段列表 FROM 表1 INNER|LEFT|RIGHT JOIN 表2 ON 表1.字段 = 表2.字段; 1.交叉连接:不适用任何匹配条件.生成笛卡尔积 sele ...

  3. Python3.5 学习三

    对文件的操作 打开模式: 1 f=open("xxx","r",encoding=="utf-8") 只读 2 f=open("x ...

  4. AngularJS源码解析3:RootScope的创建过程

    RootScopeProvider简介 RootScopeProvider是angularjs里面比较活跃的一个provider.它主要用来生成实例rootScope,它代表angularjs应用的根 ...

  5. [Objective-C语言教程]数据封装(27)

    所有Objective-C程序都由以下两个基本要素组成 - 程序语句(代码) - 这是执行操作的程序的一部分,它们被称为方法(函数). 程序数据 - 数据是受程序功能影响的程序信息. 封装是一种面向对 ...

  6. jquery scrollTop()与scrollLeft()

    1.scrollLeft() scrollLeft() 方法设置或返回被选元素的水平滚动条位置. 提示:当滚动条位于最左侧时,位置是 0. 当用于返回位置时:该方法返回第一个匹配元素的滚动条的水平位置 ...

  7. gettimeofday

    作用: 需要打印代码执行到某处的时间,或者需要计算程序执行的时间差(精确到微妙级).这时会用到gettimeofday函数,它可以返回自1970-01-01 00:00:00到现在经历的秒数. 原型: ...

  8. jenkins运行Python

    法一: 配置中构建执行Windows批处理命令如下 立即构建后,报错如下,提示python 不是内部或外部指令 修改Windows批处理指令如下: 再次“立即构建”则正常 法二: 安装Python插件 ...

  9. Python flask Reason: image not found libmysqlclient.21.dylib

    Python flask Reason: image not found libmysqlclient.21.dylib 折腾了半个下午,在这里找到了答案,在此记录一下,以免后人躺坑 错误提示: Im ...

  10. 2018南京网络赛 - Skr 回文树

    题意:求本质不同的回文串(大整数)的数字和 由回文树的性质可知贡献只在首次进入某个新节点时产生 那么只需由pos和len算出距离把左边右边删掉再算好base重复\(O(n)\)次即可 位移那段写的略微 ...