(1) MongoDB 의 자바 응용

MongoDB 는 분산 파일 을 기반 으로 저 장 된 데이터베이스 다.C + + 언어 로 작 성 됩 니 다.WEB 응용 프로그램 에 확장 가능 한 고성능 데이터 저장 솔 루 션 을 제공 하기 위 한 것 입 니 다.MongoDB 는 관계 데이터베이스 와 비관 계 데이터베이스 사이 에 있 는 제품 으로 비관 계 데이터베이스 중에서 기능 이 가장 풍부 하고 관계 데이터베이스 와 가장 비슷 하 다.MongoDB 학습 에 대해 서 는 참고 하 시기 바 랍 니 다.http://www.runoob.com/mongodb/mongodb-tutorial.html이 사이트 의 튜 토리 얼.
다음은 제 가 쓴 기본 적 인 Mongodb 데이터 베 이 스 를 응용 하 는 자바 도구 류 입 니 다.
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.MongoIterable;
import com.mongodb.client.model.CreateCollectionOptions;
import com.mongodb.client.model.Filters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bson.Document;
import org.bson.conversions.Bson;

/** * * @author Angela */
public class MongoDBUtil {

    public static void main(String args[]){
        MongoClient client=connect();
        //listDatabase(client);// 
        MongoDatabase db =getDatabase(client,"mycol");  
        //createCappedCollection(db,"p",10);
        MongoCollection<Document> collection=getCollection(db,"test");
        //dropCollection(collection);
        //listCollection(db);
        //select(collection,"likes",200);
        //update(collection,"likes",200,100,false);
        //delete(collection,"likes",100,false);
        Map<String,Object> map1=new HashMap<String,Object>();
        map1.put("title","MonogD");
        List<Integer> list=new ArrayList<Integer>();
        for(int i=0;i<5;i++){
            list.add(i);
        }
        Map<String,Object> map2=new HashMap<String,Object>();
        map2.put("title",list);
        List<Map<String,Object>> maps=new ArrayList<Map<String,Object>>();
        maps.add(map1);
        maps.add(map2);
        insert(collection,maps);
        select(collection);
        close(client);
    }

    /**    mongodb   **/
    public static MongoClient connect(){
        MongoClient client = new MongoClient( "localhost" , 27017 ); 
        System.out.println("     MongoDB   ");
        return client;
    }

    /**    mongodb   ,         **/
    public static MongoClient connect(String IP,String userName,
            String dbName,String password){
        //ServerAddress()                   
        ServerAddress serverAddress = new ServerAddress(IP,27017);  
        List<ServerAddress> addrs = new ArrayList<ServerAddress>();  
        addrs.add(serverAddress);  

        //MongoCredential.createScramSha1Credential()                     
        MongoCredential credential = MongoCredential.createScramSha1Credential(
                userName, dbName, password.toCharArray());  
        List<MongoCredential> credentials = new ArrayList<MongoCredential>();  
        credentials.add(credential);  

        //        MongoDB   
        MongoClient client = new MongoClient(addrs,credentials);  
        System.out.println("     MongoDB   ");
        return client;
    }

    /**      **/
    public static MongoDatabase getDatabase(MongoClient client,String dbName){
        //     ,          ,
        //           ,mongo        。 
        MongoDatabase db = client.getDatabase(dbName);  
        System.out.println("      "+dbName+"    ");
        return db; 
    }

    /**     **/
    public static void dropDatabase(MongoClient client,String dbName){
        client.dropDatabase(dbName);
        System.out.println("      "+dbName+"    ");
    }

    /**             **/
    public static void listDatabase(MongoClient client){
        MongoIterable<String> dbNames=client.listDatabaseNames();
        int count=0;
        System.out.println("     ");
        for(String dbName: dbNames){
            System.out.println(dbName);
            count++;
        }
        System.out.println(" "+count+"    ");
    }

    /** db        **/
    public static void createCollection(MongoDatabase db,String collectionName){
         //   com.mongodb.client.MongoDatabase    createCollection()     
         db.createCollection(collectionName);
         System.out.println(collectionName+"      ");
    }

    /** *        * @param db     * @param collectionName     * @param sizeInBytes       ,   10000 */
    public static void createCappedCollection(MongoDatabase db,
            String collectionName,long sizeInBytes){
        //   com.mongodb.client.MongoDatabase    
        //createCollection(String collectionName,CreateCollectionOptions cco)     
        CreateCollectionOptions options=new CreateCollectionOptions();
        options=options.capped(true);   //       
        options=options.sizeInBytes(sizeInBytes); //         
        db.createCollection(collectionName,options);
        System.out.println(collectionName+"        ");
    }

    /** *        * @param db     * @param collectionName     * @param sizeInBytes       ,   10000 * @param maxDocuments          */
    public static void createCappedCollection(MongoDatabase db,
            String collectionName,long sizeInBytes,long maxDocuments){
        //   com.mongodb.client.MongoDatabase    
        //createCollection(String collectionName,CreateCollectionOptions cco)     
        CreateCollectionOptions options=new CreateCollectionOptions();
        options.capped(true);//       
        options=options.sizeInBytes(sizeInBytes); //         
        options.maxDocuments(maxDocuments); //      
        db.createCollection(collectionName);
        System.out.println(collectionName+"        ");
    }

    /**  db    collectionName  **/
    public static MongoCollection<Document> getCollection(
            MongoDatabase db,String collectionName){
        //  com.mongodb.client.MongoDatabase   getCollection()          
         MongoCollection<Document> collection = db.getCollection(collectionName);
         System.out.println("   "+collectionName+"     ");
         return collection;
    }

    /**  db    **/
    public static void listCollection(MongoDatabase db){
        MongoIterable<String> collectionNames=db.listCollectionNames();
        int count=0;
        System.out.println(db+"     ");
        for(String collectionName: collectionNames){
            System.out.println(collectionName);
            count++;
        }
        System.out.println(" "+count+"   ");
    }

    /**    **/
    public static void dropCollection(MongoCollection<Document> collection){
         collection.drop();
         System.out.println(collection.getNamespace().getCollectionName()
                 +"      ");
    }

    /**      **/
    public static void insert(MongoCollection<Document> collection,
            Map<String,Object> map){
        //     org.bson.Document    key-value    
         Document document=new Document(map);
         //  com.mongodb.client.MongoCollection   
         //insertOne(Document)          
         collection.insertOne(document);
         System.out.println("      ");  
    }

    /**      **/
    public static void insert(MongoCollection<Document> collection,
            List<Map<String,Object>> maps){
         List<Document> documents = new ArrayList<Document>(); 
         for(Map<String,Object> map: maps){
             //1.      org.bson.Document    key-value   
             Document document=new Document(map);
             //2.       List<Document> 
             documents.add(document); 
         }
         // 3.   com.mongodb.client.MongoCollection   
         //insertMany(List<Document>)           
         collection.insertMany(documents); 
         System.out.println("      ");  
    }

    /**    **/
    public static void delete(MongoCollection<Document> collection,
            String fieldName,Object value,boolean isAll){
         if(isAll){
             //            
             collection.deleteMany(Filters.eq(fieldName, value));  
         }else{
             //             
             collection.deleteOne(Filters.eq(fieldName, value));  
         }
         System.out.println("      ");
    }

    /**      **/
    public static void select(MongoCollection<Document> collection){
        //   com.mongodb.client.MongoCollection     find()              。
        //         ,           。
         //       
         /** * 1.      FindIterable<Document> * 2.     MongoCursor<Document> * 3.                * */  
         FindIterable<Document> findIterable = collection.find();  
         MongoCursor<Document> mongoCursor = findIterable.iterator();  
         while(mongoCursor.hasNext()){  
            System.out.println(mongoCursor.next());  
         }  
    }

    /**             **/
    public static void select(MongoCollection<Document> collection,
            String fieldName,Object value){
         Bson bson=Filters.eq(fieldName, value);
         FindIterable<Document> findIterable = collection.find(bson);  
         MongoCursor<Document> mongoCursor = findIterable.iterator();  
         while(mongoCursor.hasNext()){  
            System.out.println(mongoCursor.next());  
         }  
    }

    /**    **/
    public static void update(MongoCollection<Document> collection,
            String fieldName,Object oldValue,Object newValue,boolean isAll){
        if(isAll){
            //   com.mongodb.client.MongoCollection     updateMany()            。
            collection.updateMany(Filters.eq(fieldName, oldValue), new Document(
                 "$set",new Document(fieldName,newValue)));
        } else{
            collection.updateOne(Filters.eq(fieldName, oldValue), new Document(
                 "$set",new Document(fieldName,newValue)));
        }
        System.out.println("      ");
    }

    /**  mongodb  **/
    public static void close(MongoClient client){
        client.close();
        System.out.println("      !");
    }

}

좋은 웹페이지 즐겨찾기