打赏

Ubuntu14.04下Mongodb的Java API编程实例(手动项目或者maven项目)

 

 

 

  不多说,直接上干货!

 

 

 

  若大家,不会安装的话,则请移步,随便挑选一种。

Ubuntu14.04下Mongodb(在线安装方式|apt-get)安装部署步骤(图文详解)(博主推荐)

Ubuntu14.04下Mongodb(离线安装方式|非apt-get)安装部署步骤(图文详解)(博主推荐)

Ubuntu14.04下Mongodb官网安装部署步骤(图文详解)(博主推荐)

 

 

 

 

第一种方式

  这里,大家可以选择在ubuntu里安装eclipse,或者,大家也可以跟我一样,在windows下的eclipse或myeclipse来连接到ubuntu。(这里是手动新建项目,不建议大家

第一步:下载Java MongoDB Driver驱动jar包,Java MongoDB Driver下载地址,默认的下载目录为~/下载或者~/Downloads 。
第二步:打开Eclipse,新建Java Project,新建Class,引入刚刚下载的jar包 
第三步:编码实现 

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

import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class TestMongoDB {

    /**
     * @param args
     */
    public static void main(String[] args) {
        insert();//插入数据。执行插入时,可将其他三句函数调用语句注释掉,下同
//      find(); //查找数据
//      update();//更新数据
//      delete();//删除数据
    }
    /**
     * 返回指定数据库中的指定集合
     * @param dbname 数据库名
     * @param collectionname 集合名
     * @return
     */
    //MongoDB无需预定义数据库和集合,在使用的时候会自动创建
    public static MongoCollection<Document> getCollection(String dbname,String collectionname){
        //实例化一个mongo客户端,服务器地址:localhost(本地),端口号:27017
        MongoClient  mongoClient=new MongoClient("localhost",27017);
        //实例化一个mongo数据库
        MongoDatabase mongoDatabase = mongoClient.getDatabase(dbname);
        //获取数据库中某个集合
        MongoCollection<Document> collection = mongoDatabase.getCollection(collectionname);
        return collection;
    }
    /**
     * 插入数据
     */
    public static void insert(){
        try{
            //连接MongoDB,指定连接数据库名,指定连接表名。
            MongoCollection<Document> collection= getCollection("test","student");
            //实例化一个文档,文档内容为{sname:'Mary',sage:25},如果还有其他字段,可以继续追加append
            Document doc1=new Document("sname","Mary").append("sage", 25);
            //实例化一个文档,文档内容为{sname:'Bob',sage:20}
            Document doc2=new Document("sname","Bob").append("sage", 20);
            List<Document> documents = new ArrayList<Document>(); 
            //将doc1、doc2加入到documents列表中
            documents.add(doc1); 
            documents.add(doc2); 
            //将documents插入集合
            collection.insertMany(documents);  
            System.out.println("插入成功"); 
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
        }
    }
    /**
     * 查询数据
     */
    public static void find(){
        try{
            MongoCollection<Document> collection = getCollection("test","student");
            //通过游标遍历检索出的文档集合 
//          MongoCursor<Document>  cursor= collection.find(new Document("sname","Mary")). projection(new Document("sname",1).append("sage",1).append("_id", 0)).iterator();   //find查询条件:sname='Mary'。projection筛选:显示sname和sage,不显示_id(_id默认会显示)
            //查询所有数据
            MongoCursor<Document>  cursor= collection.find().iterator();
            while(cursor.hasNext()){
                System.out.println(cursor.next().toJson());
            }
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
        }
    }
    /**
     * 更新数据
     */
    public static void update(){
        try{
            MongoCollection<Document> collection = getCollection("test","student");
             //更新文档   将文档中sname='Mary'的文档修改为sage=22   
             collection.updateMany(Filters.eq("sname", "Mary"), new Document("$set",new Document("sage",22)));  
             System.out.println("更新成功!");
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
        }
    }
    /**
     * 删除数据
     */
    public static void delete(){
        try{
            MongoCollection<Document> collection = getCollection("test","student");
                //删除符合条件的第一个文档  
            collection.deleteOne(Filters.eq("sname", "Bob"));  
            //删除所有符合条件的文档  
            //collection.deleteMany (Filters.eq("sname", "Bob"));
            System.out.println("删除成功!");
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
        }
    }
}

 

 

 

  每次执行完程序,都可以返回shell模式查看结果。如:在eclipse执行完更新操作后,在shell模式输入db.student.find(),可以查看student集合的所有数据,截图如下: 

 

 

 

 

 

 

 

 

 

 

 

第二种方式

  建议,大家跟随,用maven来创建项目工程。

  我经常对MongoDB进行一些基础操作,将这些常用操作合并到一个工具类中,方便自己开发使用。

Eclipse下Maven新建项目、自动打依赖jar包(包含普通项目和Web项目)

 

JAVA驱动版本:

 <!-- MongoDB驱动 -->
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.0.2</version>
 </dependency>

  这个版本,大家可以控制修改。

 

 

 

 

工具类代码如下:

package utils;

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

import org.apache.commons.configuration.CompositeConfiguration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientOptions.Builder;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;

/**
 * MongoDB工具类 Mongo实例代表了一个数据库连接池,即使在多线程的环境中,一个Mongo实例对我们来说已经足够了<br>
 * 注意Mongo已经实现了连接池,并且是线程安全的。 <br>
 * 设计为单例模式, 因 MongoDB的Java驱动是线程安全的,对于一般的应用,只要一个Mongo实例即可,<br>
 * Mongo有个内置的连接池(默认为10个) 对于有大量写和读的环境中,为了确保在一个Session中使用同一个DB时,<br>
 * DB和DBCollection是绝对线程安全的<br>
 * 
 * @author zhouls
 * @date 2017-6-2 上午11:49:49
 * @version 0.0.0
 * @Copyright (c)1997-2015 NavInfo Co.Ltd. All Rights Reserved.
 */
public enum MongoDBUtil {

    /**
     * 定义一个枚举的元素,它代表此类的一个实例
     */
    instance;

    private MongoClient mongoClient;

    static {
        System.out.println("===============MongoDBUtil初始化========================");
        CompositeConfiguration config = new CompositeConfiguration();
        try {
            config.addConfiguration(new PropertiesConfiguration("mongodb.properties"));
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
        // 从配置文件中获取属性值
        String ip = config.getString("host");
        int port = config.getInt("port");
        instance.mongoClient = new MongoClient(ip, port);

        // or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
        // List<ServerAddress> listHost = Arrays.asList(new ServerAddress("localhost", 27017),new ServerAddress("localhost", 27018));
        // instance.mongoClient = new MongoClient(listHost);

        // 大部分用户使用mongodb都在安全内网下,但如果将mongodb设为安全验证模式,就需要在客户端提供用户名和密码:
        // boolean auth = db.authenticate(myUserName, myPassword);
        Builder options = new MongoClientOptions.Builder();
        // options.autoConnectRetry(true);// 自动重连true
        // options.maxAutoConnectRetryTime(10); // the maximum auto connect retry time
        options.connectionsPerHost(300);// 连接池设置为300个连接,默认为100
        options.connectTimeout(15000);// 连接超时,推荐>3000毫秒
        options.maxWaitTime(5000); //
        options.socketTimeout(0);// 套接字超时时间,0无限制
        options.threadsAllowedToBlockForConnectionMultiplier(5000);// 线程队列数,如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。
        options.writeConcern(WriteConcern.SAFE);//
        options.build();
    }

    // ------------------------------------共用方法---------------------------------------------------
    /**
     * 获取DB实例 - 指定DB
     * 
     * @param dbName
     * @return
     */
    public MongoDatabase getDB(String dbName) {
        if (dbName != null && !"".equals(dbName)) {
            MongoDatabase database = mongoClient.getDatabase(dbName);
            return database;
        }
        return null;
    }

    /**
     * 获取collection对象 - 指定Collection
     * 
     * @param collName
     * @return
     */
    public MongoCollection<Document> getCollection(String dbName, String collName) {
        if (null == collName || "".equals(collName)) {
            return null;
        }
        if (null == dbName || "".equals(dbName)) {
            return null;
        }
        MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collName);
        return collection;
    }

    /**
     * 查询DB下的所有表名
     */
    public List<String> getAllCollections(String dbName) {
        MongoIterable<String> colls = getDB(dbName).listCollectionNames();
        List<String> _list = new ArrayList<String>();
        for (String s : colls) {
            _list.add(s);
        }
        return _list;
    }

    /**
     * 获取所有数据库名称列表
     * 
     * @return
     */
    public MongoIterable<String> getAllDBNames() {
        MongoIterable<String> s = mongoClient.listDatabaseNames();
        return s;
    }

    /**
     * 删除一个数据库
     */
    public void dropDB(String dbName) {
        getDB(dbName).drop();
    }

    /**
     * 查找对象 - 根据主键_id
     * 
     * @param collection
     * @param id
     * @return
     */
    public Document findById(MongoCollection<Document> coll, String id) {
        ObjectId _idobj = null;
        try {
            _idobj = new ObjectId(id);
        } catch (Exception e) {
            return null;
        }
        Document myDoc = coll.find(Filters.eq("_id", _idobj)).first();
        return myDoc;
    }

    /** 统计数 */
    public int getCount(MongoCollection<Document> coll) {
        int count = (int) coll.count();
        return count;
    }

    /** 条件查询 */
    public MongoCursor<Document> find(MongoCollection<Document> coll, Bson filter) {
        return coll.find(filter).iterator();
    }

    /** 分页查询 */
    public MongoCursor<Document> findByPage(MongoCollection<Document> coll, Bson filter, int pageNo, int pageSize) {
        Bson orderBy = new BasicDBObject("_id", 1);
        return coll.find(filter).sort(orderBy).skip((pageNo - 1) * pageSize).limit(pageSize).iterator();
    }

    /**
     * 通过ID删除
     * 
     * @param coll
     * @param id
     * @return
     */
    public int deleteById(MongoCollection<Document> coll, String id) {
        int count = 0;
        ObjectId _id = null;
        try {
            _id = new ObjectId(id);
        } catch (Exception e) {
            return 0;
        }
        Bson filter = Filters.eq("_id", _id);
        DeleteResult deleteResult = coll.deleteOne(filter);
        count = (int) deleteResult.getDeletedCount();
        return count;
    }

    /**
     * FIXME
     * 
     * @param coll
     * @param id
     * @param newdoc
     * @return
     */
    public Document updateById(MongoCollection<Document> coll, String id, Document newdoc) {
        ObjectId _idobj = null;
        try {
            _idobj = new ObjectId(id);
        } catch (Exception e) {
            return null;
        }
        Bson filter = Filters.eq("_id", _idobj);
        // coll.replaceOne(filter, newdoc); // 完全替代
        coll.updateOne(filter, new Document("$set", newdoc));
        return newdoc;
    }

    public void dropCollection(String dbName, String collName) {
        getDB(dbName).getCollection(collName).drop();
    }

    /**
     * 关闭Mongodb
     */
    public void close() {
        if (mongoClient != null) {
            mongoClient.close();
            mongoClient = null;
        }
    }

    /**
     * 测试入口
     * 
     * @param args
     */
    public static void main(String[] args) {

        String dbName = "GC_MAP_DISPLAY_DB";
        String collName = "COMMUNITY_BJ";
        MongoCollection<Document> coll = MongoDBUtil.instance.getCollection(dbName, collName);

        // 插入多条
        // for (int i = 1; i <= 4; i++) {
        // Document doc = new Document();
        // doc.put("name", "zhoulf");
        // doc.put("school", "NEFU" + i);
        // Document interests = new Document();
        // interests.put("game", "game" + i);
        // interests.put("ball", "ball" + i);
        // doc.put("interests", interests);
        // coll.insertOne(doc);
        // }

        // // 根据ID查询
        // String id = "556925f34711371df0ddfd4b";
        // Document doc = MongoDBUtil2.instance.findById(coll, id);
        // System.out.println(doc);

        // 查询多个
        // MongoCursor<Document> cursor1 = coll.find(Filters.eq("name", "zhoulf")).iterator();
        // while (cursor1.hasNext()) {
        // org.bson.Document _doc = (Document) cursor1.next();
        // System.out.println(_doc.toString());
        // }
        // cursor1.close();

        // 查询多个
        // MongoCursor<Person> cursor2 = coll.find(Person.class).iterator();

        // 删除数据库
        // MongoDBUtil2.instance.dropDB("testdb");

        // 删除表
        // MongoDBUtil2.instance.dropCollection(dbName, collName);

        // 修改数据
        // String id = "556949504711371c60601b5a";
        // Document newdoc = new Document();
        // newdoc.put("name", "时候");
        // MongoDBUtil.instance.updateById(coll, id, newdoc);

        // 统计表
        // System.out.println(MongoDBUtil.instance.getCount(coll));

        // 查询所有
        Bson filter = Filters.eq("count", 0);
        MongoDBUtil.instance.find(coll, filter);

    }

}

 

  更多大家,自行去尝试!

posted @ 2017-06-02 22:10  大数据和AI躺过的坑  阅读(781)  评论(0编辑  收藏  举报