进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. 电表读数归零回滚SQL处理算法

    在采集电表数据的时候,可以发现有些电表设备读数会发生回滚.这时候,如果单纯的累加计算用电量,就会出现负值.当然,这也许和电表的质量有关系. “RTQty”(当前读到的读数).“LastQty”(上次读 ...

  2. CheckBox使用记录

    页面显示 页面代码 <div> <div><input type="checkbox" value="" class=" ...

  3. leetcode 实现strStr()

    实现strStr()函数. 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始).如果不存在,则返回 ...

  4. 基于ASP.NET生成二维码详细源码

    详细链接:https://shop499704308.taobao.com/?spm=a1z38n.10677092.card.11.594c1debsAGeakusing System; using ...

  5. A - 还是畅通工程(最小生成树)

    点击打开链接 某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离.省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并 ...

  6. PRINT语句详解

    首先摘自联机丛书中的PRINT语法如下: PRINT msg_str | @local_variable | string_exp  以上可看出PRINT语句的输出参数均为字符或字符串的常量或变量 - ...

  7. robot framework踩坑记录

    一.报错:FAIL : 'Return' is a reserved keyword. 给Retrun加上中括号即可 二.报错:True != true 三.报错 /Library/Python/2. ...

  8. 常见的HTTP请求应答返回码列表

        200      OK 请求成功.一般用于GET与POST请求 300 Multiple Choices 多种选择.请求的资源可包括多个位置,相应可返回一个资源特征与地址的列表用于用户终端(例 ...

  9. linuxea:ELK5.5-elasticsearch-x-pack破解

    本站采用知识共享署名-非商业性使用-相同方式共享国际许可协议4.0 进行许可 本文作者:www.linuxea.com for Mark 文章链接:https://www.linuxea.com/17 ...

  10. 查看inux系统类型和版本

    当我们使用一台新的linux服务器的时候,为了区分他们的命令,我们首先第一步就是要搞清楚这个系统的类型和版本号,据此再来使用对应的命令. 下面来看看可以使用以下基本命令来查看 Linux 发行版名称和 ...