• mongo小记


    进mongo
    
    mongo
    
    先添加admin表的账号密码
    
    1. use admin
    2. 
    db.createUser(  
      {  
        user: "admin",  
        pwd: "admin",  
        roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]  
      }  
    )  
    3. db.auth('admin','admin')
    在admin登录情况下,切换到自己数据库操作
    
    1. use test
    2. db.createUser({user:'test',pwd:'test',roles:[{role:"dbOwner",db:"test"}]})
    退出重新登录
    
    1. mongo
    2. use test
    3. 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自己写一个吧

  • 相关阅读:
    震撼光效:Geomerics Enlighten Demo at GDC 2010
    CryEngine3SDK尝鲜
    李嘉诚:没有人愿意贫穷,但出路在哪(转自意林)
    OGRE手册脚本<texture_unit>
    《OgreBeginner'sGuidede》第七章翻译(原)
    李彦宏15年前搜索专利曝光:谷歌创始人拾惠(转)
    中国大侠vs生化战士(转)
    OGRE主要渲染流程简介(转)
    好运设计(史铁生散文)
    游戏设计的秘密——翻译GDC2010 blizzard的一个演讲【转】
  • 原文地址:https://www.cnblogs.com/hawk-whu/p/6771711.html
Copyright © 2020-2023  润新知