• JAVA 操作MongoDB


    MongoDB的3.x版本Java驱动相对2.x做了全新的设计,类库和使用方法上有很大区别。例如用Document替换BasicDBObject、通过Builders类构建Bson替代直接输入$命令等,本文整理了基于3.2版本的常用增删改查操作的使用方法。为了避免冗长的篇幅,分为增删改、查询、聚合、地理索引等几部分。本篇主要介绍记录一下自己的一个mongodb的工具类,测试了简单的一些增、删、改以及建索引的一些方法。

    创建一个maven项目,添加依赖

    [java] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
    1. <dependencies>  
    2.     <dependency>  
    3.         <groupId>org.mongodb</groupId>  
    4.         <artifactId>mongodb-driver</artifactId>  
    5.         <version>3.2.2</version>  
    6.     </dependency>  
    7. </dependencies>  

    非maven项目可自行下载jar包

     http://central.maven.org/maven2/org/mongodb/mongo-java-driver/3.2.2/mongo-java-driver-3.2.2.jar

    mongodb工具类:

      1 package com.wd.util;
      2 
      3 import java.util.ArrayList;
      4 import java.util.Arrays;
      5 import java.util.List;
      6 import org.bson.Document;
      7 import org.bson.conversions.Bson;
      8 import org.bson.types.ObjectId;
      9 
     10 import com.mongodb.BasicDBObject;
     11 import com.mongodb.DB;
     12 import com.mongodb.DBCollection;
     13 import com.mongodb.DBCursor;
     14 import com.mongodb.MongoClient;
     15 import com.mongodb.MongoClientOptions;
     16 import com.mongodb.MongoClientOptions.Builder;
     17 import com.mongodb.WriteConcern;
     18 import com.mongodb.client.AggregateIterable;
     19 import com.mongodb.client.FindIterable;
     20 import com.mongodb.client.ListIndexesIterable;
     21 import com.mongodb.client.MongoCollection;
     22 import com.mongodb.client.MongoCursor;
     23 import com.mongodb.client.MongoDatabase;
     24 import com.mongodb.client.MongoIterable;
     25 import com.mongodb.client.model.Filters;
     26 import static com.mongodb.client.model.Filters.*;  
     27 import static com.mongodb.client.model.Projections.*;  
     28 import static com.mongodb.client.model.Sorts.*;
     29 import static com.mongodb.client.model.Accumulators.*;  
     30 import static com.mongodb.client.model.Aggregates.*; 
     31 import com.mongodb.client.model.IndexOptions;
     32 import com.mongodb.client.model.Projections;
     33 import com.mongodb.client.model.UpdateOptions;
     34 import com.mongodb.client.model.Updates.*;
     35 import com.mongodb.client.result.DeleteResult;
     36 import com.wd.backend.model.AffiliationJG;
     37 import com.wd.backend.model.AffiliationList;
     38 
     39 import net.sf.json.JSONArray;
     40 import net.sf.json.JSONObject;
     41 import net.sf.json.JsonConfig;
     42 
     43 
     44 public enum MongoUtil {
     45      /**
     46      * 定义一个枚举的元素,它代表此类的一个实例
     47      */
     48     instance;
     49 
     50     private static MongoClient mongoClient;
     51 
     52     static {
     53         System.out.println("===============MongoDBUtil初始化========================");
     54         String ip = "192.168.1.75";
     55         int port =27017;
     56         instance.mongoClient = new MongoClient(ip, port);
     57         // 大部分用户使用mongodb都在安全内网下,但如果将mongodb设为安全验证模式,就需要在客户端提供用户名和密码:
     58         // boolean auth = db.authenticate(myUserName, myPassword);
     59         Builder options = new MongoClientOptions.Builder();
     60         options.cursorFinalizerEnabled(true);
     61         // options.autoConnectRetry(true);// 自动重连true
     62         // options.maxAutoConnectRetryTime(10); // the maximum auto connect retry time
     63         options.connectionsPerHost(300);// 连接池设置为300个连接,默认为100
     64         options.connectTimeout(30000);// 连接超时,推荐>3000毫秒
     65         options.maxWaitTime(5000); //
     66         options.socketTimeout(0);// 套接字超时时间,0无限制
     67         options.threadsAllowedToBlockForConnectionMultiplier(5000);// 线程队列数,如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。
     68         options.writeConcern(WriteConcern.SAFE);//
     69         options.build();
     70     }
     71 
     72     // ------------------------------------共用方法---------------------------------------------------
     73     /**
     74      * 获取DB实例 - 指定DB
     75      * 
     76      * @param dbName
     77      * @return
     78      */
     79     public MongoDatabase getDB(String dbName) {
     80         if (dbName != null && !"".equals(dbName)) {
     81             MongoDatabase database = mongoClient.getDatabase(dbName);
     82             return database;
     83         }
     84         return null;
     85     }
     86 
     87     /**
     88      * 获取collection对象 - 指定Collection
     89      * 
     90      * @param collName
     91      * @return
     92      */
     93     public MongoCollection<Document> getCollection(String dbName, String collName) {
     94         if (null == collName || "".equals(collName)) {
     95             return null;
     96         }
     97         if (null == dbName || "".equals(dbName)) {
     98             return null;
     99         }
    100         MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collName);
    101         return collection;
    102     }
    103 
    104     /**
    105      * 查询DB下的所有表名
    106      */
    107     public List<String> getAllCollections(String dbName) {
    108         MongoIterable<String> colls = getDB(dbName).listCollectionNames();
    109         List<String> _list = new ArrayList<String>();
    110         for (String s : colls) {
    111             _list.add(s);
    112         }
    113         return _list;
    114     }
    115 
    116     /**
    117      * 获取所有数据库名称列表
    118      * 
    119      * @return
    120      */
    121     public MongoIterable<String> getAllDBNames() {
    122         MongoIterable<String> s = mongoClient.listDatabaseNames();
    123         return s;
    124     }
    125 
    126     /**
    127      * 删除一个数据库
    128      */
    129     public void dropDB(String dbName) {
    130         getDB(dbName).drop();
    131     }
    132 
    133     /**
    134      * 查找对象 - 根据主键_id
    135      * 
    136      * @param collection
    137      * @param id
    138      * @return
    139      */
    140     public Document findById(MongoCollection<Document> coll, String id) {
    141         ObjectId _idobj = null;
    142         try {
    143             _idobj = new ObjectId(id);
    144         } catch (Exception e) {
    145             return null;
    146         }
    147         Document myDoc = coll.find(Filters.eq("_id", _idobj)).first();
    148         return myDoc;
    149     }
    150 
    151     /** 统计数 */
    152     public int getCount(MongoCollection<Document> coll) {
    153         int count = (int) coll.count();
    154         return count;
    155     }
    156 
    157     /** 条件查询 */
    158     public MongoCursor<Document> find(MongoCollection<Document> coll, Bson filter) {
    159         return coll.find(filter).iterator();
    160     }
    161 
    162     /** 分页查询 */
    163     public MongoCursor<Document> findByPage(MongoCollection<Document> coll, Bson filter, int pageNo, int pageSize) {
    164         Bson orderBy = new BasicDBObject("_id", 1);
    165         return coll.find(filter).sort(orderBy).skip((pageNo - 1) * pageSize).limit(pageSize).iterator();
    166     }
    167     
    168 
    169     /**
    170      * 通过ID删除
    171      * 
    172      * @param coll
    173      * @param id
    174      * @return
    175      */
    176     public int deleteById(MongoCollection<Document> coll, String id) {
    177         int count = 0;
    178         ObjectId _id = null;
    179         try {
    180             _id = new ObjectId(id);
    181         } catch (Exception e) {
    182             return 0;
    183         }
    184         Bson filter = Filters.eq("_id", _id);
    185         DeleteResult deleteResult = coll.deleteOne(filter);
    186         count = (int) deleteResult.getDeletedCount();
    187         return count;
    188     }
    189 
    190     /**
    191      * FIXME
    192      * 
    193      * @param coll
    194      * @param id
    195      * @param newdoc
    196      * @return
    197      */
    198     public Document updateById(MongoCollection<Document> coll, String id, Document newdoc) {
    199         ObjectId _idobj = null;
    200         try {
    201             _idobj = new ObjectId(id);
    202         } catch (Exception e) {
    203             return null;
    204         }
    205         Bson filter = Filters.eq("_id", _idobj);
    206         // coll.replaceOne(filter, newdoc); // 完全替代
    207         coll.updateOne(filter, new Document("$set", newdoc));
    208         return newdoc;
    209     }
    210 
    211     public void dropCollection(String dbName, String collName) {
    212         getDB(dbName).getCollection(collName).drop();
    213     }
    214 
    215     /**
    216      * 关闭Mongodb
    217      */
    218     public void close() {
    219         if (mongoClient != null) {
    220             mongoClient.close();
    221             mongoClient = null;
    222         }
    223     }
    224 
    225     /**
    226      * 测试入口
    227      * 
    228      * @param args
    229      * @throws CloneNotSupportedException 
    230      */
    231     public static void main(String[] args) {
    232         
    233         String dbName = "test";
    234         String collName = "wd_paper_scie";
    235         MongoCollection<Document> coll = MongoUtil.instance.getCollection(dbName, collName);
    236         //coll.createIndex(new Document("validata",1));//创建索引
    237         //coll.createIndex(new Document("id",1));
    238        // coll.createIndex(new Document("ut_wos",1),new IndexOptions().unique(true));//创建唯一索引
    239         //coll.dropIndexes();//删除索引
    240         //coll.dropIndex("validata_1");//根据索引名删除某个索引
    241         ListIndexesIterable<Document> list = coll.listIndexes();//查询所有索引
    242         for (Document document : list) {
    243             System.out.println(document.toJson());
    244         }
    245         coll.find(Filters.and(Filters.eq("x", 1), Filters.lt("y", 3)));
    246         coll.find(and(eq("x", 1), lt("y", 3)));
    247         coll.find().sort(ascending("title"));  
    248         coll.find().sort(new Document("id",1)); 
    249         coll.find(new Document("$or", Arrays.asList(new Document("owner", "tom"), new Document("words", new Document("$gt", 350)))));
    250         coll.find().projection(fields(include("title", "owner"), excludeId()));  
    251         // coll.updateMany(Filters.eq("validata", 1), Updates.set("validata", 0));
    252         //coll.updateMany(Filters.eq("validata", 1), new Document("$unset", new Document("jigou", "")));//删除某个字段
    253         //coll.updateMany(Filters.eq("validata", 1), new Document("$rename", new Document("affiliation", "affiliation_full")));//修改某个字段名
    254         //coll.updateMany(Filters.eq("validata", 1), new Document("$rename", new Document("affiliationMeta", "affiliation")));
    255         //coll.updateMany(Filters.eq("validata", 1), new Document("$set", new Document("validata", 0)));//修改字段值
    256 //        MongoCursor<Document> cursor1 =coll.find(Filters.eq("ut_wos", "WOS:000382970200003")).iterator();
    257 //        while(cursor1.hasNext()){
    258 //            Document sd=cursor1.next();
    259 //            System.out.println(sd.toJson());
    260 //            coll.insertOne(sd);
    261 //        }
    262        
    263 //        MongoCursor<Document> cursor1 =coll.find(Filters.elemMatch("affInfo", Filters.eq("firstorg", 1))).iterator();
    264 //        while(cursor1.hasNext()){
    265 //            Document sd=cursor1.next();
    266 //            System.out.println(sd.toJson());
    267 //        }
    268         //查询只返回指定字段
    269        // MongoCursor<Document> doc= coll.find().projection(Projections.fields(Projections.include("ut_wos","affiliation"),Projections.excludeId())).iterator();
    270         //"ut_wos" : "WOS:000382970200003"
    271        //coll.updateMany(Filters.eq("validata", 1), new Document("$set", new Document("validata", 0)));
    272         //coll.updateMany(Filters.eq("validata", 0), new Document("$rename", new Document("sid", "ssid")), new UpdateOptions().upsert(false));
    273         //coll.updateOne(Filters.eq("ut_wos", "WOS:000382970200003"), new Document("$set", new Document("validata", 0)));
    274         //long isd=coll.count(Filters.elemMatch("affInfo", Filters.elemMatch("affiliationJGList", Filters.eq("sid", 0))));
    275        // System.out.println(isd);
    276         //MongoCursor<Document> doc= coll.find(Filters.elemMatch("affInfo", Filters.elemMatch("affiliationJGList", Filters.ne("sid", 0)))).projection(Projections.fields(Projections.elemMatch("affInfo"),Projections.excludeId())).iterator();
    277 //       MongoCursor<Document> doc= coll.find().projection(Projections.include("affInfo","ssid")).iterator();
    278 //       while(doc.hasNext()){
    279 //            Document sd=doc.next();
    280 //            System.out.println(sd.toJson());
    281 //            
    282 //        }
    283         MongoUtil.instance.close();
    284         // 插入多条
    285 //         for (int i = 1; i <= 4; i++) {
    286 //         Document doc = new Document();
    287 //         doc.put("name", "zhoulf");
    288 //         doc.put("school", "NEFU" + i);
    289 //         Document interests = new Document();
    290 //         interests.put("game", "game" + i);
    291 //         interests.put("ball", "ball" + i);
    292 //         doc.put("interests", interests);
    293 //         coll.insertOne(doc);
    294 //         }
    295 //       
    296        /* MongoCursor<Document> sd =coll.find().iterator();
    297         while(sd.hasNext()){
    298             Document doc = sd.next();
    299             String id =  doc.get("_id").toString();
    300             List<AffiliationJG> list = new ArrayList<AffiliationJG>();
    301             AffiliationJG jg = new AffiliationJG();
    302             jg.setAddress("123");
    303             jg.setCid(2);
    304             jg.setCname("eeee");
    305             jg.setSid(3);
    306             jg.setSname("rrrr");
    307             AffiliationJG jg2 = new AffiliationJG();
    308             jg2.setAddress("3242");
    309             jg2.setCid(2);
    310             jg2.setCname("ers");
    311             jg2.setSid(3);
    312             jg2.setSname("rasdr");
    313             list.add(jg);
    314             list.add(jg2);
    315             AffiliationList af = new AffiliationList();
    316             af.setAffiliationAuthos("33333");
    317             af.setAffiliationinfo("asdsa");
    318             af.setAffiliationJGList(list);
    319             JSONObject json = JSONObject.fromObject(af);
    320             doc.put("affInfo", json);
    321             MongoDBUtil.instance.updateById(coll, id, doc);
    322         }*/
    323         
    324 //        Bson bs = Filters.eq("name", "zhoulf");
    325 //        coll.find(bs).iterator();
    326         // // 根据ID查询
    327         // String id = "556925f34711371df0ddfd4b";
    328         // Document doc = MongoDBUtil2.instance.findById(coll, id);
    329         // System.out.println(doc);
    330 
    331         // 查询多个
    332         // MongoCursor<Document> cursor1 = coll.find(Filters.eq("name", "zhoulf")).iterator();
    333         // while (cursor1.hasNext()) {
    334         // org.bson.Document _doc = (Document) cursor1.next();
    335         // System.out.println(_doc.toString());
    336         // }
    337         // cursor1.close();
    338 
    339         // 查询多个
    340 //         MongoCursor<WdPaper> cursor2 = coll.find(WdPaper.class).iterator();
    341 //         while(cursor2.hasNext()){
    342 //             WdPaper doc = cursor2.next();
    343 //             System.out.println(doc.getUt_wos());
    344 //         }
    345         // 删除数据库
    346         // MongoDBUtil2.instance.dropDB("testdb");
    347 
    348         // 删除表
    349         // MongoDBUtil2.instance.dropCollection(dbName, collName);
    350 
    351         // 修改数据
    352         // String id = "556949504711371c60601b5a";
    353         // Document newdoc = new Document();
    354         // newdoc.put("name", "时候");
    355         // MongoDBUtil.instance.updateById(coll, id, newdoc);
    356 
    357         // 统计表
    358          //System.out.println(MongoDBUtil.instance.getCount(coll));
    359 
    360         // 查询所有
    361 //        Bson filter = Filters.eq("count", 0);
    362 //        MongoDBUtil.instance.find(coll, filter);
    363 
    364     }
    365 
    366 }
  • 相关阅读:
    error C2054: 在“inline”之后应输入“(”
    SendInput模拟键盘操作
    获取广电高清直播源
    Lua使用luasocket http请求例子
    枚举所有继承特定接口的类
    Stream Byte[] 转换
    async await
    C# ServiceStack.Redis 操作对象List
    resharper安装后,一不小心点错了(选择了object browser)
    fiddler 挂载 JS文件
  • 原文地址:https://www.cnblogs.com/sa-dan/p/6836055.html
Copyright © 2020-2023  润新知