首页 > 代码库 > mongo小记

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自己写一个吧

mongo小记