java 实现操作mongodb的连接,增删查改

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Agly_Clarlie/article/details/56311949

java 实现操作mongodb的连接,增删查改

mongodb的jar包下载
java mongodb 驱动
https://oss.sonatype.org/content/repositories/releases/org/mongodb/mongodb-driver/3.4.1/
我下载的是(mongo-java-driver-3.0.1.jar)

java 实现mongodb的连接关闭操作,写一个mongodbHelper

package com.java.dao;

import com.mongodb.MongoClient;

import com.mongodb.client.MongoDatabase;

public class MongoHelper {

        static final String DBName = "weibo";
        static final String ServerAddress = "127.0.0.1"; 
        static final int PORT = 27017;

        public MongoHelper(){
        }

        public MongoClient getMongoClient( ){
            MongoClient mongoClient = null;
            try {
                  // 连接到 mongodb 服务
                mongoClient = new MongoClient(ServerAddress, PORT); 
                System.out.println("Connect to mongodb successfully");
            } catch (Exception e) {
                System.err.println(e.getClass().getName() + ": " + e.getMessage());
            }
            return mongoClient;
        }

        public MongoDatabase getMongoDataBase(MongoClient mongoClient) {  
            MongoDatabase mongoDataBase = null;
            try {  
                if (mongoClient != null) {  
                      // 连接到数据库
                    mongoDataBase = mongoClient.getDatabase(DBName);  
                    System.out.println("Connect to DataBase successfully");
                } else {  
                    throw new RuntimeException("MongoClient不能够为空");  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
            }
            return mongoDataBase;
        }  

        public void closeMongoClient(MongoDatabase mongoDataBase,MongoClient mongoClient ) {  
            if (mongoDataBase != null) {  
                mongoDataBase = null;  
            }  
            if (mongoClient != null) {  
                mongoClient.close();  
            }  
            System.out.println("CloseMongoClient successfully");  

        }  
}

连接成功后进行增删查改操作
这是基本增删查改的接口

package com.java.dao;

import java.util.Map;


import org.bson.Document;

import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;

/**
 * Dao 层接口
 * 
 */
public interface MongoDao {
    /**
     * Get Data BY ID
     * 
     * @param db
     * @param table
     * @param Id
     * @throws Exception 
     */
    public Map<String,Integer> queryByID(MongoDatabase db, String table, Object Id) throws Exception;

    /**
     * Insert Data
     * 
     * @param db
     * @param table
     * @param document
     */
    public boolean insert(MongoDatabase db, String table, Document doc);

    /**
     * Delete Many Data.if doc is empty will delete all Data
     * 
     * @param db
     * @param table
     * @param document
     */
    public boolean delete(MongoDatabase db, String table, BasicDBObject doc);

    /**
     * Update All Data
     * 
     * @param db
     * @param table
     * @param oldDoc
     * @param newDoc
     */
    public boolean update(MongoDatabase db, String table, BasicDBObject oldDoc,
            BasicDBObject newDoc);

}

实现上面的接口并且扩充方法

package com.java.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.bson.Document;

import com.java.exception.CustomException;
import com.java.service.JsonStrToMap;
import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;

/**
 * 实现接口
 * @author iiip
 *
 */
public class MongoDaoImpl implements MongoDao {

    @Override
    public Map<String,Integer> queryByID(MongoDatabase db, String table, Object Id) throws Exception{
        MongoCollection<Document> collection = db.getCollection(table);
        BasicDBObject query = new BasicDBObject("_id", Id);
        //  DBObject接口和BasicDBObject对象:表示一个具体的记录,BasicDBObject实现了DBObject,是key-value的数据结构,用起来和HashMap是基本一致的。
        FindIterable<Document> iterable = collection.find(query);

//      for (Document dd : iterable) {
//          int dudu = dd.getInteger("上海"); // 读取响应的数据
//          System.out.println("dudududu:"+dudu);
//      }

        Map<String,Integer> jsonStrToMap = null;
        MongoCursor<Document> cursor = iterable.iterator();
        while (cursor.hasNext()) {
            Document user = cursor.next();
            String jsonString = user.toJson();
            jsonStrToMap = JsonStrToMap.jsonStrToMap(jsonString);//这里用到我自己写的方法,主要是包json字符串转换成map格式,为后面做准备,方法放在后面
        }
        System.out.println("检索ID完毕");

        return jsonStrToMap;
    }

    /**
     * 根据一个doc,来检索,当doc是空的时候检索全部
     * @param db
     * @param table
     * @param doc
     */
    public List<Map<String,Integer>>  queryByDoc(MongoDatabase db, String table, BasicDBObject doc) {
        MongoCollection<Document> collection = db.getCollection(table);
        FindIterable<Document> iterable = collection.find(doc);
         /** 
         * 1. 获取迭代器FindIterable<Document> 
         * 2. 获取游标MongoCursor<Document> 
         * 3. 通过游标遍历检索出的文档集合 
         * */  

        List<Map<String,Integer>> list = new ArrayList<Map<String,Integer>>();
        MongoCursor<Document> cursor = iterable.iterator();
        while (cursor.hasNext()) {
            Document user = cursor.next();
            String jsonString = user.toJson();
            Map<String, Integer> jsonStrToMap = JsonStrToMap.jsonStrToMap(jsonString);
            list.add(jsonStrToMap);
        }
        System.out.println("检索doc完毕");
        return list;
    }

    /**
     *  检索全部并返回迭代器
     * @param db
     * @param table
     */
    public List<Map<String,Integer>> queryAll(MongoDatabase db, String table) {
        MongoCollection<Document> collection = db.getCollection(table);
        FindIterable<Document> iterable = collection.find();

        List<Map<String,Integer>> list = new ArrayList<Map<String,Integer>>();
        MongoCursor<Document> cursor = iterable.iterator();
        while (cursor.hasNext()) {
            Document user = cursor.next();
            String jsonString = user.toJson();
            Map<String, Integer> jsonStrToMap = JsonStrToMap.jsonStrToMap(jsonString);
            list.add(jsonStrToMap);
        }
        System.out.println("检索全部完毕");
        return list;
    }

    /**
     * 便利迭代器FindIterable<Document> 
     */
    public void printFindIterable(FindIterable<Document> iterable){
        MongoCursor<Document> cursor = iterable.iterator();
        while (cursor.hasNext()) {
            Document user = cursor.next();
            System.out.println(user.toJson());
        }
        cursor.close();
    }


    @Override
    public boolean insert(MongoDatabase db, String table, Document document) {
        MongoCollection<Document> collection = db.getCollection(table);
        collection.insertOne(document);
        long count = collection.count(document);
//      System.out.println(collection.getNamespace());//weibo.area
//      System.out.println(collection.getClass());//class com.mongodb.MongoCollectionImpl
//      System.out.println(collection.getDocumentClass());//class org.bson.Document
//      System.out.println(collection.getWriteConcern());//WriteConcern{w=1, wtimeout=0, fsync=false, j=false
//      System.out.println(collection.getWriteConcern().getW());//1

        System.out.println("count: "+count);
        if(count == 1){
            System.out.println("文档插入成功");
            return true;
        }else{
            System.out.println("文档插入成功");
            return false;
        }

    }

    /**
     * insert many
     * @param db
     * @param table
     * @param document
     */
    public boolean insertMany(MongoDatabase db, String table, List<Document> documents ) {

        MongoCollection<Document> collection = db.getCollection(table);
        long preCount = collection.count();
        collection.insertMany(documents);
        long nowCount = collection.count();
        System.out.println("插入的数量: "+(nowCount-preCount));
        if((nowCount-preCount) == documents.size() ){
            System.out.println("文档插入多个成功");
            return true;
        }else{
            System.out.println("文档插入多个失败");
            return false;
        }

    }

    @Override
    public boolean delete(MongoDatabase db, String table, BasicDBObject document) {
        MongoCollection<Document> collection = db.getCollection(table);
        DeleteResult deleteManyResult = collection.deleteMany(document);
        long deletedCount = deleteManyResult.getDeletedCount();
        System.out.println("删除的数量: "+deletedCount);
        if(deletedCount > 0){
            System.out.println("文档删除多个成功");
            return true;
        }else{
            System.out.println("文档删除多个失败");
            return false;
        }
    }

    /**
     * 删除一个
     * @param db
     * @param table
     * @param document
     */
    public boolean deleteOne(MongoDatabase db, String table, BasicDBObject document) {
        MongoCollection<Document> collection = db.getCollection(table);
        DeleteResult deleteOneResult = collection.deleteOne(document);
        long deletedCount = deleteOneResult.getDeletedCount();
        System.out.println("删除的数量: "+deletedCount);
        if(deletedCount == 1){
            System.out.println("文档删除一个成功");
            return true;
        }else{
            System.out.println("文档删除一个失败");
            return false;
        }
    }


    @Override
    public boolean update(MongoDatabase db, String table, BasicDBObject whereDoc,BasicDBObject updateDoc) {
            MongoCollection<Document> collection = db.getCollection(table);  
             UpdateResult updateManyResult = collection.updateMany(whereDoc, new Document("$set",updateDoc)); 
             long modifiedCount = updateManyResult.getModifiedCount();
             System.out.println("修改的数量: "+modifiedCount);

            if (modifiedCount > 0){
                System.out.println("文档更新多个成功");
                return true;
            }else{
                System.out.println("文档更新失败");
                return false;
            }
    }


    /**
     * update one Data
     * @param db
     * @param table
     * @param whereDoc
     * @param updateDoc
     */
    public boolean updateOne(MongoDatabase db, String table, BasicDBObject whereDoc,BasicDBObject updateDoc) {
            MongoCollection<Document> collection = db.getCollection(table);  
             UpdateResult updateOneResult = collection.updateOne(whereDoc, new Document("$set",updateDoc)); 
             long modifiedCount = updateOneResult.getModifiedCount();
             System.out.println("修改的数量: "+modifiedCount);
             if(modifiedCount == 1){
                System.out.println("文档更新一个成功");
                 return true;
             }else{
                System.out.println("文档更新失败");
                 return false;
             }
    }
    /**
     * create collection
     * @param db
     * @param table
     */
    public void createCol(MongoDatabase db, String table) {
         db.createCollection(table);
        System.out.println("集合创建成功");
    }

    /**
     * drop a collection
     * @param db
     * @param table
     */
    public void dropCol(MongoDatabase db, String table) {
        db.getCollection(table).drop();
        System.out.println("集合删除成功");

    }

}

前面用到的一个类方法JsonStrToMap.jsonStrToMap

package com.java.service;

import java.util.HashMap;
import java.util.Map;

import com.mongodb.util.JSON;

public class JsonStrToMap {

    /**
     * json 字符串转化为map格式
     * @param jsonString
     * @return
     */

    public static Map<String, Integer> jsonStrToMap(String jsonString) {
        Object parseObj = JSON.parse(jsonString); // 反序列化 把json 转化为对象
        Map<String, Integer> map = (HashMap<String, Integer>) parseObj; // 把对象转化为map
        return map;
    }

}

测试方法

package com.java.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.bson.Document;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;
import com.mongodb.util.JSON;


/**
 * 测试类
 * @author koo
 *
 */
public class MainMonHelperImpl {
    public static void main(String[] args) {
        MongoHelper mongoHelper = new MongoHelper();
        MongoClient mongoClient = mongoHelper.getMongoClient();
        MongoDatabase mongoDataBase = mongoHelper.getMongoDataBase(mongoClient);
        MongoDaoImpl mongoDaoImpl = new MongoDaoImpl();

// *  直接用BasicDBObject进行CRUD

//      mongoDaoImpl.insert(mongoDataBase, table, new Document(areaMap));//插入document

//      mongoDaoImpl.queryByID(mongoDataBase, table, 1);//检索event_id,注意id类型是字符串还是int
//      BasicDBObject document2 = new BasicDBObject("likes",1000);
//      document2.append("event_id", "55");
//      mongoDaoImpl.queryByDoc(mongoDataBase, table, document2);//检索doc,可以根据doc(key,value)来查找,当doc是空的时候,检索全部
//      mongoDaoImpl.queryAll(mongoDataBase, table); //查询全部

//      BasicDBObject document3 = new BasicDBObject("likes",200);
//      mongoDaoImpl.delete(mongoDataBase, table, document3);//删除doc 的全部信息,当doc 是空,则删除全部
//      BasicDBObject document3 = new BasicDBObject("likes", 1000);
//      mongoDaoImpl.deleteOne(mongoDataBase, table, document3);//删除doc 的一个信息

//      更新文档   将文档中likes=100的文档修改为likes=200   
//      BasicDBObject whereDoc = new BasicDBObject("likes",1000);
//      BasicDBObject updateDoc = new BasicDBObject("likes",255);
//      mongoDaoImpl.update(mongoDataBase, table, whereDoc, updateDoc);//更新全部,查找到oldDoc的数据,更新newDoc的数据
//      BasicDBObject whereDoc = new BasicDBObject("likes",255);
//      BasicDBObject updateDoc = new BasicDBObject("event_id",205);
//      mongoDaoImpl.updateOne(mongoDataBase, table, whereDoc, updateDoc);//更新全部,查找到oldDoc的数据,更新newDoc的数据


//------------------------------------------------
        /**
         * 使用map 进行CRUD操作
         */

//      System.out.println("测试map");
//      Map<String, Object> areaMap1 = new HashMap<String,Object>();
//      areaMap1.put("_id", 2);
//      areaMap1.put("北京", 5);
//      areaMap1.put("上海", 14);
//      areaMap1.put("广州",8);
//      areaMap1.put("深圳",0.5);


         //把map反序列化
//      System.out.println("map parse: " + JSON.parse(JSON.serialize(areaMap)));  

        // 根据map 到mongodb查询
//     FindIterable<Document> queryByDocResult = mongoDaoImpl.queryByDoc(mongoDataBase, areaTable, new BasicDBObject(areaMap1));
//     mongoDaoImpl.printFindIterable(queryByDocResult);


        //   插入map 到mongodb
//      mongoDaoImpl.insert(mongoDataBase, areaTable, new Document(areaMap1));

//      Map<String, Object> areaMap2 = new HashMap<String,Object>();
//      Map<String, Object> areaMap3 = new HashMap<String,Object>();
//      areaMap2.put("_id", 10);
//      areaMap2.put("北京", 5);
//
//      areaMap3.put("_id", 11);
//      areaMap3.put("北京", 5);
//      List<Document> docList = new ArrayList<Document>();
//      docList.add(new Document(areaMap2));
//      docList.add(new Document(areaMap3));
//      mongoDaoImpl.insertMany(mongoDataBase, areaTable, docList);

        //   根据map 删除mongodb
//      mongoDaoImpl.delete(mongoDataBase, areaTable, new BasicDBObject(areaMap1));
//      mongoDaoImpl.deleteOne(mongoDataBase, areaTable, new BasicDBObject(areaMap1));

        //根据map 更新mongodb
//      Map<String, Object> updateDoc = new HashMap<String,Object>();
//      Map<String, Object> wehereDoc = new HashMap<String,Object>();
//      wehereDoc.put("_id", 4);
//      updateDoc.put("上海",25);
//      mongoDaoImpl.update(mongoDataBase, areaTable, new BasicDBObject(wehereDoc), new BasicDBObject(updateDoc));
//      mongoDaoImpl.updateOne(mongoDataBase, areaTable, new BasicDBObject(wehereDoc), new BasicDBObject(updateDoc));


        //检索全部
//      FindIterable<Document> queryAllResult = mongoDaoImpl.queryAll(mongoDataBase, areaTable);
//      mongoDaoImpl.printFindIterable(queryAllResult);
//      mongoHelper.closeMongoClient(mongoDataBase,mongoClient);

    }

}

参考:
mongoUtil java heleper
http://blog.csdn.net/guoxingege/article/details/47439581

语法:
http://www.runoob.com/mongodb/mongodb-java.html

文档
http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/

java mongodb 驱动
https://oss.sonatype.org/content/repositories/releases/org/mongodb/mongodb-driver/3.4.1/

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页