java操作mongoDB工具类以及测试类

java操作mongoDB工具类:

 package com.nxin.iot.cloud.common.util;
 
 import com.google.common.collect.Lists;
 import com.mongodb.MongoClient;
 import com.mongodb.MongoCredential;
 import com.mongodb.ServerAddress;
 import com.mongodb.client.FindIterable;
 import com.mongodb.client.MongoCollection;
 import com.mongodb.client.MongoCursor;
 import com.mongodb.client.MongoDatabase;
 import com.mongodb.client.model.Filters;
 
 import com.nxin.iot.cloud.common.constant.MongoConstant;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.log4j.Logger;
 import org.bson.Document;
 import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
 
 /**
 * create by 黄建和 2018/5/28
 */
 public class MongoDBUtil {
 
     private static final String PLEASE_SEND_IP = "没有传入ip或者端口号";
     private static final String PWD_UN_ERR = "用户账号密码不匹配";
     private static final String PLEASE_INSTANCE_MONGOCLIENT = "请实例化MongoClient";
     private static final String PLEASE_SEND_MONGO_REPOSITORY = "请指定要删除的mongo库";
     private static final String DELETE_MONGO_REPOSITORY_EXCEPTION = "删除mongo库异常";
     private static final String DELETE_MONGO_REPOSITORY_SUCCESS = "批量删除mongo库成功";
     private static final String NOT_DELETE_MONGO_REPOSITORY = "未删除mongo库";
     private static final String DELETE_MONGO_REPOSITORY = "成功删除mongo库:";
     private static final String CREATE_MONGO_COLLECTION_NOTE = "请指定要创建的库";
     private static final String NO_THIS_MONGO_DATABASE = "未找到指定mongo库";
     private static final String CREATE_MONGO_COLLECTION_SUCCESS = "创建mongo库成功";
     private static final String CREATE_MONGO_COLLECTION_EXCEPTION = "创建mongo库错误";
     private static final String NOT_CREATE_MONGO_COLLECTION = "未创建mongo库collection";
     private static final String CREATE_MONGO_COLLECTION_SUCH = "创建mongo库collection:";
     private static final String NO_FOUND_MONGO_COLLECTION = "未找到mongo库collection";
     private static final String INSERT_DOCUMEN_EXCEPTION = "插入文档失败";
     private static final String INSERT_DOCUMEN_SUCCESSS = "插入文档成功";
     private static final String COLLECTION_IS_NULL = "documentMongoCollection为空";
 
 
     private static final Logger logger = Logger.getLogger(MongoDBUtil.class);
 
     private MongoDBUtil(){
 
     }
 
     private static class SingleHolder{
         private static MongoDBUtil mongoDBUtil = new MongoDBUtil();
     }
 
     public static MongoDBUtil instance(){
 
         return SingleHolder.mongoDBUtil;
     }
 
     /**
     * 获取mongoDB连接
     * @param host
     * @param port
     * @return
     */
     public MongoClient getMongoConnect(String host,Integer port){
 
         if(StringUtils.isBlank(host) || null == port){
             logger.error(PLEASE_SEND_IP);
             return null;
         }
 
         return new MongoClient(host, port);
     }
 
     /**
     * 获取mongoDB连接
     * @param serverAddress
     * @param credentials
     * @return
     */
     @SuppressWarnings("deprecation")
     public MongoClient getMongoConnect(ServerAddress serverAddress,List<MongoCredential> credentials){
 
         if(null == serverAddress){
             logger.error(PLEASE_SEND_IP);
             return null;
         }
 
         if(null == credentials || credentials.size() == 0) {
             logger.error(PWD_UN_ERR);
             return null;
         }
 
         return new MongoClient(serverAddress, credentials);
     }
 
 
     /**
     * 批量删除mongo库
     * @param mongoClient
     * @param dbNames
     * @return
     */
     public String bulkDropDataBase(MongoClient mongoClient,String...dbNames){
 
         if(null == mongoClient) return PLEASE_INSTANCE_MONGOCLIENT;
 
         if(null==dbNames || dbNames.length==0){
             return PLEASE_SEND_MONGO_REPOSITORY;
         }
         try {
             Arrays.asList(dbNames).forEach(dbName -> mongoClient.dropDatabase(dbName));
             logger.info(DELETE_MONGO_REPOSITORY_SUCCESS);
         }catch (Exception e){
             e.printStackTrace();
             logger.error(DELETE_MONGO_REPOSITORY_EXCEPTION);
         }
         return dbNames == null ? NOT_DELETE_MONGO_REPOSITORY:DELETE_MONGO_REPOSITORY + String.join(",",dbNames);
     }
 
 
     /**
     * 创建指定database的collection
     * @param mongoClient
     * @param dbName
     * @param collections
     * @return
     */
     public String createCollections(MongoClient mongoClient,String dbName,String...collections){
 
         if(null == mongoClient) return PLEASE_INSTANCE_MONGOCLIENT;
 
         if(null==collections || collections.length==0){
             return CREATE_MONGO_COLLECTION_NOTE;
         }
 
         MongoDatabase mongoDatabase = mongoClient.getDatabase(dbName);
         if(null == mongoDatabase) return NO_THIS_MONGO_DATABASE;
 
         try {
             Arrays.asList(collections).forEach(collection ->  mongoDatabase.createCollection(collection));
             logger.info(CREATE_MONGO_COLLECTION_SUCCESS);
             return collections == null ? NOT_CREATE_MONGO_COLLECTION:CREATE_MONGO_COLLECTION_SUCH + String.join(",",collections);
         }catch (Exception e){
             e.printStackTrace();
             logger.error(CREATE_MONGO_COLLECTION_EXCEPTION);
         }
 
         return null;
     }
 
     /**
     * 获取MongoCollection
     * @param mongoClient
     * @param dbName
     * @param collection
     * @return
     */
     public MongoCollection<Document> getMongoCollection(MongoClient mongoClient,String dbName,String collection){
 
         if(null == mongoClient) return null;
 
         if(StringUtils.isBlank(dbName)) return null;
 
         if(StringUtils.isBlank(collection)) return null;
 
         MongoDatabase mongoDatabase = mongoClient.getDatabase(dbName);
 
         MongoCollection<Document> collectionDocuments = mongoDatabase.getCollection(collection);
 
         if(null == collectionDocuments) return null;
 
         return collectionDocuments;
     }
 
 
     /**
     * 插入文档数据
     * @param mongoCollection
     * @param params
     */
     public void insertDoucument(final MongoCollection<Document> mongoCollection, final Map<String,Object> params){
 
 
         if(null == mongoCollection) return;
 
 
         try {
             Document document = new Document();
             params.keySet().stream().forEach(field -> document.append(field, params.get(field)));
 
             List<Document> documents = Lists.newArrayList();
             documents.add(document);
             mongoCollection.insertMany(documents);
             logger.info(INSERT_DOCUMEN_SUCCESSS);
         }catch (Exception e){
             e.printStackTrace();
             logger.error(INSERT_DOCUMEN_EXCEPTION);
         }
     }
 
     /**
     * 更新文档
     * @param mongoCollection
     * @param conditionParams
     * @param updateParams
     */
     public void updateDocument(final MongoCollection<Document> mongoCollection,final Map<String,Object> conditionParams,
                             final Map<String,Object> updateParams
     ){
 
         if(null == mongoCollection) return;
 
         if (null == conditionParams) return;
 
         if (null == updateParams) return;
 
 
         Document conditonDocument = new Document();
         conditionParams.keySet().stream().filter(p -> null != p).forEach(o -> {
             conditonDocument.append(o,conditionParams.get(o));
         });
 
 
         Document updateDocument = new Document();
         updateParams.keySet().stream().filter(p -> null != p).forEach(o -> {
             updateDocument.append(o,updateParams.get(o));
         });
         mongoCollection.updateMany(conditonDocument,new Document("$set",updateDocument));
     }
 
     /**
     *删除文档
     * @param mongoCollection
     * @param multiple
     * @param conditionParams
     * @return
     */
     public long deleteDocument(final MongoCollection<Document> mongoCollection,final boolean multiple,
                             final Map<String,Object> conditionParams){
 
         if(null == mongoCollection) return 0;
 
         if(null == conditionParams) return 0;
 
         Document document = new Document();
 
         conditionParams.keySet().stream().filter(p -> null != p).forEach(o -> {
             document.append(o,conditionParams.get(o));
         });
 
         if(multiple) {
             return mongoCollection.deleteMany(document).getDeletedCount();
         }
 
         //删除文档第一条
         return mongoCollection.deleteOne(document).getDeletedCount();
     }
 
     /**
     * 查询文档
     * @param mongoCollection
     * @param conditionParams
     * @param limit
     * @param skip
     * @param sortParams
     */
     public MongoCursor<Document> queryDocument(final MongoCollection<Document> mongoCollection, final Map<String,Object> conditionParams,
                                             final Integer limit, final Integer skip, final Map<String,Integer> sortParams,
                                             final Map<String,Integer> gtLtOrOtherParams,final String compareField
     ){
 
         if(null == mongoCollection) return null;
         /**
         * 1. 获取迭代器FindIterable<Document>
         * 2. 获取游标MongoCursor<Document>
         * 3. 通过游标遍历检索出的文档集合
         * */
 
         Document document = new Document();
         if(null != conditionParams && !conditionParams.isEmpty()) {
 
             conditionParams.forEach((k,v)  -> {
                 if(StringUtils.isNotBlank(k)) document.append(k,v);
             });
         }
 
         Document compareDocument = null;
         if(null != gtLtOrOtherParams && !gtLtOrOtherParams.isEmpty()) {
 
             Document gtOrLtDoc = new Document();
             gtLtOrOtherParams.forEach((k,v) -> {
                 if(StringUtils.isNotBlank(k)) gtOrLtDoc.append(k,v);
             });
             compareDocument = new Document(compareField,gtOrLtDoc);
         }else {
             compareDocument = new Document();
         }
 
         FindIterable<Document> findIterable = mongoCollection.find(Filters.and(document,compareDocument));
 
         Document sortDocument = new Document();
         if(null != sortParams && !sortParams.isEmpty()) {
             sortParams.forEach((k,v) -> {
                 if(StringUtils.isNotBlank(k)) sortDocument.append(k,v);
             });
             findIterable.sort(sortDocument);
         }
 
         if(null != limit) findIterable = findIterable.limit(limit);
 
         if(null != skip) findIterable = findIterable.skip(skip);
 
         return findIterable.iterator();
 
     }
 
     /**
     * 查询文档
     * @param mongoCollection
     * @return
     */
     public MongoCursor<Document> queryDocument(final MongoCollection<Document> mongoCollection
     ){
 
         if(null == mongoCollection) return null;
         /**
         * 1. 获取迭代器FindIterable<Document>
         * 2. 获取游标MongoCursor<Document>
         * 3. 通过游标遍历检索出的文档集合
         * */
 
         FindIterable<Document> findIterable = mongoCollection.find();
 
         return findIterable.iterator();
 
     }
 
     /**
     * 查询文档
     * @param mongoCollection
     * @param conditionParams
     * @return
     */
     public MongoCursor<Document> queryDocument(final MongoCollection<Document> mongoCollection, final Map<String,Object> conditionParams){
 
         if(null == mongoCollection) return null;
         /**
         * 1. 获取迭代器FindIterable<Document>
         * 2. 获取游标MongoCursor<Document>
         * 3. 通过游标遍历检索出的文档集合
         * */
 
         Document document = new Document();
         if(null != conditionParams && !conditionParams.isEmpty()) {
 
             conditionParams.forEach((k,v)  -> {
                 if(StringUtils.isNotBlank(k)) document.append(k,v);
             });
         }
 
         return mongoCollection.find(Filters.and(document)).iterator();
     }
 
     public MongoCursor<Document> queryDocument(final MongoCollection<Document> mongoCollection, final Map<String,Object> conditionParams,
                                             final Integer limit, final Integer skip){
 
         if(null == mongoCollection) return null;
         /**
         * 1. 获取迭代器FindIterable<Document>
         * 2. 获取游标MongoCursor<Document>
         * 3. 通过游标遍历检索出的文档集合
         * */
 
         Document document = new Document();
         if(null != conditionParams && !conditionParams.isEmpty()) {
 
             conditionParams.forEach((k,v)  -> {
                 if(StringUtils.isNotBlank(k)) document.append(k,v);
             });
         }
 
         FindIterable<Document> findIterable = mongoCollection.find(Filters.and(document));
 
         if(null != limit) findIterable = findIterable.limit(limit);
 
         if(null != skip) findIterable = findIterable.skip(skip);
         return findIterable.iterator();
     }
 
     public MongoCursor<Document> queryDocument(final MongoCollection<Document> mongoCollection,final Integer limit, final Integer skip){
 
         if(null == mongoCollection) return null;
         /**
         * 1. 获取迭代器FindIterable<Document>
         * 2. 获取游标MongoCursor<Document>
         * 3. 通过游标遍历检索出的文档集合
         * */
 
         FindIterable<Document> findIterable = mongoCollection.find();
 
         if(null != limit) findIterable = findIterable.limit(limit);
 
         if(null != skip) findIterable = findIterable.skip(skip);
         return findIterable.iterator();
     }
 
     public MongoCursor<Document> queryDocument(final MongoCollection<Document> mongoCollection, final Map<String,Integer> sortParams,boolean sort){
 
         if(null == mongoCollection) return null;
         /**
         * 1. 获取迭代器FindIterable<Document>
         * 2. 获取游标MongoCursor<Document>
         * 3. 通过游标遍历检索出的文档集合
         * */
 
 
         FindIterable<Document> findIterable = mongoCollection.find();
 
         Document sortDocument = new Document();
         if(null != sortParams && !sortParams.isEmpty()) {
             sortParams.forEach((k,v) -> {
                 if(StringUtils.isNotBlank(k)) sortDocument.append(k,v);
             });
             findIterable.sort(sortDocument);
         }
 
         return findIterable.iterator();
     }
 
     public MongoCursor<Document> queryDocument(final MongoCollection<Document> mongoCollection, final Map<String,Object> conditionParams,
                                             final Integer limit, final Integer skip,final Map<String,Integer> sortParams){
 
         if(null == mongoCollection) return null;
         /**
         * 1. 获取迭代器FindIterable<Document>
         * 2. 获取游标MongoCursor<Document>
         * 3. 通过游标遍历检索出的文档集合
         * */
 
         Document document = new Document();
         if(null != conditionParams && !conditionParams.isEmpty()) {
 
             conditionParams.forEach((k,v)  -> {
                 if(StringUtils.isNotBlank(k)) document.append(k,v);
             });
         }
 
         FindIterable<Document> findIterable = mongoCollection.find(Filters.and(document));
 
         Document sortDocument = new Document();
         if(null != sortParams && !sortParams.isEmpty()) {
             sortParams.forEach((k,v) -> {
                 if(StringUtils.isNotBlank(k)) sortDocument.append(k,v);
             });
             findIterable.sort(sortDocument);
         }
 
         if(null != limit) findIterable = findIterable.limit(limit);
 
         if(null != skip) findIterable = findIterable.skip(skip);
         return findIterable.iterator();
     }
 
     public MongoCursor<Document> queryDocument(final MongoCollection<Document> mongoCollection,
                                             final Integer limit, final Integer skip,final Map<String,Integer> sortParams){
 
         if(null == mongoCollection) return null;
         /**
         * 1. 获取迭代器FindIterable<Document>
         * 2. 获取游标MongoCursor<Document>
         * 3. 通过游标遍历检索出的文档集合
         * */
 
         FindIterable<Document> findIterable = mongoCollection.find();
 
         Document sortDocument = new Document();
         if(null != sortParams && !sortParams.isEmpty()) {
             sortParams.forEach((k,v) -> {
                 if(StringUtils.isNotBlank(k)) sortDocument.append(k,v);
             });
             findIterable.sort(sortDocument);
         }
 
         if(null != limit) findIterable = findIterable.limit(limit);
 
         if(null != skip) findIterable = findIterable.skip(skip);
         return findIterable.iterator();
     }
 
     public MongoCursor<Document> queryDocument(final MongoCollection<Document> mongoCollection,
                                             final Map<String,Integer> gtLtOrOtherParams,final String compareField
     ){
 
         if(null == mongoCollection) return null;
         /**
         * 1. 获取迭代器FindIterable<Document>
         * 2. 获取游标MongoCursor<Document>
         * 3. 通过游标遍历检索出的文档集合
         * */
 
         Document compareDocument = null;
         if(null != gtLtOrOtherParams && !gtLtOrOtherParams.isEmpty()) {
 
             Document gtOrLtDoc = new Document();
             gtLtOrOtherParams.forEach((k,v) -> {
                 if(StringUtils.isNotBlank(k)) gtOrLtDoc.append(k,v);
             });
             compareDocument = new Document(compareField,gtOrLtDoc);
         }else {
             compareDocument = new Document();
         }
 
         return mongoCollection.find(Filters.and(compareDocument)).iterator();
 
     }
 
     public MongoCursor<Document> queryDocument(final MongoCollection<Document> mongoCollection,final Integer limit,
                                             final Integer skip,final Map<String,Integer> gtLtOrOtherParams,final String compareField
     ){
 
         if(null == mongoCollection) return null;
         /**
         * 1. 获取迭代器FindIterable<Document>
         * 2. 获取游标MongoCursor<Document>
         * 3. 通过游标遍历检索出的文档集合
         * */
 
 
         Document compareDocument = null;
         if(null != gtLtOrOtherParams && !gtLtOrOtherParams.isEmpty()) {
 
             Document gtOrLtDoc = new Document();
             gtLtOrOtherParams.forEach((k,v) -> {
                 if(StringUtils.isNotBlank(k)) gtOrLtDoc.append(k,v);
             });
             compareDocument = new Document(compareField,gtOrLtDoc);
         }else {
             compareDocument = new Document();
         }
 
         FindIterable<Document> findIterable = mongoCollection.find(compareDocument);
 
         if(null != limit) findIterable = findIterable.limit(limit);
 
         if(null != skip) findIterable = findIterable.skip(skip);
 
         return findIterable.iterator();
 
     }
 
     public MongoCursor<Document> queryDocument(final MongoCollection<Document> mongoCollection,
                                             final Integer limit, final Integer skip, final Map<String,Integer> sortParams,
                                             final Map<String,Integer> gtLtOrOtherParams,final String compareField
     ){
 
         if(null == mongoCollection) return null;
         /**
         * 1. 获取迭代器FindIterable<Document>
         * 2. 获取游标MongoCursor<Document>
         * 3. 通过游标遍历检索出的文档集合
         * */
 
         Document compareDocument = null;
         if(null != gtLtOrOtherParams && !gtLtOrOtherParams.isEmpty()) {
 
             Document gtOrLtDoc = new Document();
             gtLtOrOtherParams.forEach((k,v) -> {
                 if(StringUtils.isNotBlank(k)) gtOrLtDoc.append(k,v);
             });
             compareDocument = new Document(compareField,gtOrLtDoc);
         }else {
             compareDocument = new Document();
         }
 
         FindIterable<Document> findIterable = mongoCollection.find(compareDocument);
 
         Document sortDocument = new Document();
         if(null != sortParams && !sortParams.isEmpty()) {
             sortParams.forEach((k,v) -> {
                 if(StringUtils.isNotBlank(k)) sortDocument.append(k,v);
             });
             findIterable.sort(sortDocument);
         }
 
         if(null != limit) findIterable = findIterable.limit(limit);
 
         if(null != skip) findIterable = findIterable.skip(skip);
 
         return findIterable.iterator();
 
     }
 
     public MongoCursor<Document> queryDocument(final MongoCollection<Document> mongoCollection, final Map<String,Object> conditionParams,
                                             final Map<String,Integer> gtLtOrOtherParams,final String compareField
     ){
 
         if(null == mongoCollection) return null;
         /**
         * 1. 获取迭代器FindIterable<Document>
         * 2. 获取游标MongoCursor<Document>
         * 3. 通过游标遍历检索出的文档集合
         * */
 
         Document document = new Document();
         if(null != conditionParams && !conditionParams.isEmpty()) {
 
             conditionParams.forEach((k,v)  -> {
                 if(StringUtils.isNotBlank(k)) document.append(k,v);
             });
         }
 
         Document compareDocument = null;
         if(null != gtLtOrOtherParams && !gtLtOrOtherParams.isEmpty()) {
 
             Document gtOrLtDoc = new Document();
             gtLtOrOtherParams.forEach((k,v) -> {
                 if(StringUtils.isNotBlank(k)) gtOrLtDoc.append(k,v);
             });
             compareDocument = new Document(compareField,gtOrLtDoc);
         }else {
             compareDocument = new Document();
         }
 
         FindIterable<Document> findIterable = mongoCollection.find(Filters.and(document,compareDocument));
 
         return findIterable.iterator();
 
     }
 
     public MongoCursor<Document> queryDocument(final MongoCollection<Document> mongoCollection, final Map<String,Object> conditionParams,
                                             final Integer limit, final Integer skip,final Map<String,Integer> gtLtOrOtherParams,final String compareField
     ){
 
         if(null == mongoCollection) return null;
         /**
         * 1. 获取迭代器FindIterable<Document>
         * 2. 获取游标MongoCursor<Document>
         * 3. 通过游标遍历检索出的文档集合
         * */
 
         Document document = new Document();
         if(null != conditionParams && !conditionParams.isEmpty()) {
 
             conditionParams.forEach((k,v)  -> {
                 if(StringUtils.isNotBlank(k)) document.append(k,v);
             });
         }
 
         Document compareDocument = null;
         if(null != gtLtOrOtherParams && !gtLtOrOtherParams.isEmpty()) {
 
             Document gtOrLtDoc = new Document();
             gtLtOrOtherParams.forEach((k,v) -> {
                 if(StringUtils.isNotBlank(k)) gtOrLtDoc.append(k,v);
             });
             compareDocument = new Document(compareField,gtOrLtDoc);
         }else {
             compareDocument = new Document();
         }
 
         FindIterable<Document> findIterable = mongoCollection.find(Filters.and(document,compareDocument));
 
         if(null != limit) findIterable = findIterable.limit(limit);
 
         if(null != skip) findIterable = findIterable.skip(skip);
 
         return findIterable.iterator();
 
     }
 
     /**
     * 统计指定表的数量
     * @param documentMongoCollection
     * @param conditionParams
     * @param gtLtOrOtherParams
     * @param compareField
     * @return
     */
     public Long countTable(final MongoCollection<Document> documentMongoCollection,final Map<String,Object> conditionParams,
                         final Map<String,Integer> gtLtOrOtherParams,final String compareField){
 
 
         if(null == documentMongoCollection) {
             logger.error(COLLECTION_IS_NULL);
             return 0L;
         }
 
         Document document = new Document();
         if(null != conditionParams && !conditionParams.isEmpty()) {
 
             conditionParams.forEach((k,v)  -> {
                 if(StringUtils.isNotBlank(k)) document.append(k,v);
             });
         }
 
         Document compareDocument = null;
         if(null != gtLtOrOtherParams && !gtLtOrOtherParams.isEmpty()) {
 
             Document gtOrLtDoc = new Document();
             gtLtOrOtherParams.forEach((k,v) -> {
                 if(StringUtils.isNotBlank(k)) gtOrLtDoc.append(k,v);
             });
             compareDocument = new Document(compareField,gtOrLtDoc);
         }else {
             compareDocument = new Document();
         }
 
         return documentMongoCollection.count(Filters.and(document,compareDocument));
     }
 
     /**
     * 统计指定表的数量
     * @param documentMongoCollection
     * @param conditionParams
     * @return
     */
     public Long countTable(final MongoCollection<Document> documentMongoCollection,final Map<String,Object> conditionParams){
 
 
         if(null == documentMongoCollection) {
             logger.error(COLLECTION_IS_NULL);
             return 0L;
         }
 
         Document document = new Document();
         if(null != conditionParams && !conditionParams.isEmpty()) {
 
             conditionParams.forEach((k,v)  -> {
                 if(StringUtils.isNotBlank(k)) document.append(k,v);
             });
         }
 
         return documentMongoCollection.count(Filters.and(document));
     }
 
     /**
     * 统计指定表的数量
     * @param documentMongoCollection
     * @param gtLtOrOtherParams
     * @param compareField
     * @return
     */
     public Long countTable(final MongoCollection<Document> documentMongoCollection,
                         final Map<String,Integer> gtLtOrOtherParams,final String compareField){
 
 
         if(null == documentMongoCollection) {
             logger.error(COLLECTION_IS_NULL);
             return 0L;
         }
 
 
         Document compareDocument = null;
         if(null != gtLtOrOtherParams && !gtLtOrOtherParams.isEmpty()) {
 
             Document gtOrLtDoc = new Document();
             gtLtOrOtherParams.forEach((k,v) -> {
                 if(StringUtils.isNotBlank(k)) gtOrLtDoc.append(k,v);
             });
             compareDocument = new Document(compareField,gtOrLtDoc);
         }else {
             compareDocument = new Document();
         }
 
         return documentMongoCollection.count(Filters.and(compareDocument));
     }
 }

mongo用到的比较常量定义

 package constant;
 
 public enum MongoConstant {
 
     GT("$gt"),LT("$lt"),GTE("$gte"),LTE("$lte");
     
     private String compareIdentify;  
     
     MongoConstant(String compareIdentify) {  
         this.compareIdentify = compareIdentify;  
     }  
     
     public String getCompareIdentify() {
         return compareIdentify;
     }
 }

工具类的测试类

 package com.nxin.iot.cloud.common;
 
 import com.google.common.collect.Maps;
 import com.mongodb.MongoClient;
 import com.mongodb.client.MongoCollection;
 import com.mongodb.client.MongoCursor;
 import com.mongodb.client.model.Filters;
 import com.nxin.iot.cloud.common.constant.MongoConstant;
 import com.nxin.iot.cloud.common.util.MongoDBUtil;
 import org.bson.Document;
 
 import java.util.Date;
 import java.util.Map;
 
 /**
 * Created by Nxin on 2018/5/28.
 */
 public class TestMongo {
 
     public static void main(String[] args) {
 
         try {
 
             //无用户密码验证实例
             MongoClient client = MongoDBUtil.instance().getMongoConnect("127.0.0.1",27017);
             //需要用户密码实例
             //         MongoCredential credential = MongoCredential.createCredential("user", "database", "password".toCharArray());
             //         MongoDBUtil.instance().getMongoConnect(new ServerAddress("ip", 27017), Arrays.asList(credential));
 
             MongoCollection<Document> documentMongoCollection = MongoDBUtil.instance().getMongoCollection(client,"hjh","test");
 
 
             //插入文档
 //                    for(int i=0;i<=10;i++) {
 //                         Map<String, Object> params = Maps.newHashMap();
 //                         params.put("qq", "hjh");
 //                         params.put("time", new Date());
 //                         params.put("name", "bb" + i);
 //                        params.put("num", i);
 //                         MongoDBUtil.instance().insertDoucument(documentMongoCollection, params);
 //                     }
 //
 //                    for(int i=0;i<=10;i++) {
 //                         Map<String, Object> params = Maps.newHashMap();
 //                         params.put("qq", "hh");
 //                         params.put("time", new Date());
 //                         params.put("name", "cc" + i);
 //                        params.put("num", i);
 //                         MongoDBUtil.instance().insertDoucument(documentMongoCollection, params);
 //                     }
 
             //更改文档
             //         Map<String,Object> condParams = Maps.newHashMap();
             //         condParams.put("description","database");
             //         condParams.put("aa","bbb");
             //         Map<String,Object> updateParams = Maps.newHashMap();
             //         updateParams.put("description","eee");
             //         MongoDBUtil.instance().updateDocument(documentMongoCollection,condParams,updateParams);
 
             //删除文档数据
             //         Map<String,Object> condParams = Maps.newHashMap();
             //         condParams.put("qq",1111);
             //
             //         MongoDBUtil.instance().deleteDocument(documentMongoCollection,true,condParams);
 
             //查询文档
 //            Map<String,Object> condParams = Maps.newHashMap();
 //            condParams.put("qq","hjh");
 //
 //            Map<String,Integer> sortParams = Maps.newHashMap();
 //            sortParams.put("num",-1);
 //            //         sortParams.put("name",1);
 //            Map<String,Integer> compareParams = Maps.newHashMap();
 //            compareParams.put(MongoConstant.GT.getCompareIdentify(),5);
 //            compareParams.put(MongoConstant.LTE.getCompareIdentify(),10);
 //            MongoCursor<Document> mongoCursor = MongoDBUtil.instance().queryDocument(documentMongoCollection,condParams,2,2,sortParams,compareParams,"num");
 //            while(mongoCursor.hasNext()){
 //                System.out.println(mongoCursor.next());
 //            }
 
             //统计数量
             Map<String,Object> condParams = Maps.newHashMap();
             condParams.put("qq","hjh");
             Map<String,Integer> compareParams = Maps.newHashMap();
             compareParams.put(MongoConstant.GT.getCompareIdentify(),5);
             compareParams.put(MongoConstant.LTE.getCompareIdentify(),10);
             long l = MongoDBUtil.instance().countTable(documentMongoCollection,condParams,compareParams,"num");
             System.err.print(l);
 
         } catch (Exception e) {
             System.err.println(e.getClass().getName() + ": " + e.getMessage());
         }
 
     }
 }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,236评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,867评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,715评论 0 340
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,899评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,895评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,733评论 1 283
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,085评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,722评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,025评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,696评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,816评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,447评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,057评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,009评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,254评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,204评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,561评论 2 343

推荐阅读更多精彩内容