Java操作mongodeDB 2.6の一般的なAPIの使い方

7742 ワード

mongodbの場合、学習方式と学習関係型データベースの差はあまりありません
最初はinsert、find、update、removeの方法を学び、それからページング、ソート、インデックス、それから主従レプリケーション、コピーセット、スライスなどです.
最後に、Java、PHP、node.jsなど、さまざまなドライバを提供することで、いわゆる高度な使い方を練習します.
また、Oracleに対してPLSQL Developerがあり、MySQLにはHeidiSQLがあります
mongodyも例外ではありません.そのグラフィックツールにはmongoVUEというものがあります.私は1.5.3解読版を使っています(15日ごとにレジストリを変更しなければならないわけではありません).
以下にJavaを例に、よくある操作mongodb APIの使い方を示します.
package com.jadyer.test;
 
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
 
import org.bson.types.ObjectId;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
 
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.WriteResult;
import com.mongodb.util.JSON;
 
/**
 * mongoDB Java    
 * @see ----------------------------------------------------------------------------------------
 * @see   
 * @see 1)  https://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2008plus-2.6.1.zip
 * @see 2)       D:\Develop\mongoDB\ ,       path=D:\Develop\mongoDB\bin
 * @see      CMD              >mongod --version
 * @see 3)  D:\Develop\mongoDBData\   ,    mongoDB    
 * @see 4)   bat  ,      mongoDB             
 * @see         mongo_client.bat   -->mongo 127.0.0.1:27017/admin
 * @see         mongo_db.bat   ------>mongod --dbpath D:\Develop\mongoDBData --rest
 * @see    :  [--rest]         mongoDB Web   http://127.0.0.1:28017/
 * @see ----------------------------------------------------------------------------------------
 * @see Java  
 * @see      mongoDB Java   ,    http://docs.mongodb.org/ecosystem/drivers/java/
 * @see ----------------------------------------------------------------------------------------
 * @create May 15, 2014 10:17:30 PM
 * @author   <http://blog.csdn.net/jadyer>
 */
public class MongoDBTest {
    private static MongoClient mongoClient;
    private static DB db;
     
    /**
     *        
     */
    @BeforeClass
    public static void globalInit(){
        try {
            //mongoClient = new MongoClient(Arrays.asList(new ServerAddress("127.0.0.1", 27017), new ServerAddress("127.0.0.1", 27018), new ServerAddress("127.0.0.1", 27019)));
            mongoClient = new MongoClient("127.0.0.1", 27017);
        } catch (UnknownHostException e) {
            System.err.println("mongoDB      ");
        }
        db = mongoClient.getDB("mydemo");
    }
     
     
    /**
     *        
     */
    @AfterClass
    public static void globalDestroy(){
        mongoClient.close();
    }
     
     
    /**
     *        
     */
    @Test
    public void getMetaData(){
        //             
        for(String collectionName : db.getCollectionNames()){
            System.out.println("mydemo          :[" + collectionName + "]");
        }
        //          
        DBCollection collection = db.getCollection("person");
        DBCursor cursor = collection.find();
        try{
            while(cursor.hasNext()){
                System.out.println("person      name --[" + cursor.next().get("name") + "]");
            }
        }finally{
            cursor.close();
        }
        System.out.println("person        ----------->" + cursor.count());
        System.out.println("person         JSON  -->" + JSON.serialize(cursor));
    }
     
     
    /**
     *       "moive"  
     */
    @Test
    public void createCollection(){
        db.createCollection("movie", new BasicDBObject());
    }
     
     
    /**
     *  "moive"      
     */
    @Test
    public void insertDocument(){
        DBObject doc = new BasicDBObject();
        doc.put("name", "24");
        doc.put("season", "ninth");
        doc.put("score", 88);
        List<String> actorList = new ArrayList<String>();
        actorList.add("Jack Bauer");
        actorList.add("Counter Terrorist Unit");
        doc.put("actor", actorList);
        db.getCollection("movie").insert(doc);
    }
     
     
    /**
     *       
     */
    @Test
    public void insertBatchDocument(){
        List<DBObject> docList = new ArrayList<DBObject>();
        DBObject doc11 = new BasicDBObject("name", "Prison Break").append("season", "fourth").append("score", 99);
        DBObject doc22 = new BasicDBObject("name", "Game of Thrones").append("season", "third").append("score", 92);
        docList.add(doc11);
        docList.add(doc22);
        db.getCollection("movie").insert(docList);
    }
     
     
    /**
     *   _id    
     */
    @Test
    public void deleteById(){
        WriteResult result = db.getCollection("movie").remove(new BasicDBObject("_id", new ObjectId("5374c6dc5030e0ea4dac8907")));
        System.out.println("            :" + result.getN());
    }
     
     
    /**
     *         
     */
    @Test
    public void deleteByData(){
        DBObject doc = new BasicDBObject();
        doc.put("name", "Prison Break");
        WriteResult result = db.getCollection("movie").remove(doc);
        System.out.println("            :" + result.getN());
    }
     
     
    /**
     *     
     * @see   email  
     */
    @Test
    public void update(){
        DBObject doc = new BasicDBObject();
        doc.put("$set", new BasicDBObject("email", "[email protected]"));
        WriteResult result = db.getCollection("movie").update(new BasicDBObject(), doc, false, true);
        System.out.println("            :" + result.getN());
    }
     
     
    /**
     *   "moive"    key
     */
    @Test
    public void getKey(){
        DBObject keys = new BasicDBObject();
        keys.put("_id", false);
        keys.put("name", true);
        //keys.put("score", true);
        //           ,            key
        DBCursor cursor = db.getCollection("movie").find(null, keys);
        try{
            while(cursor.hasNext()){
                DBObject object = cursor.next();
                System.out.println("    name=" + object.get("name") + ", score=" + object.get("score"));
            }
        }finally{
            cursor.close();
        }
    }
     
     
    /**
     *   "moive"        95 key
     */
    @Test
    public void getKeyUseScore(){
        DBObject ref = new BasicDBObject();
        ref.put("score", new BasicDBObject("$lte", 95));
        DBCursor cursor = db.getCollection("movie").find(ref, null);
        try{
            while(cursor.hasNext()){
                DBObject object = cursor.next();
                System.out.println("    name=" + object.get("name") + ", score=" + object.get("score"));
            }
        }finally{
            cursor.close();
        }
    }
     
     
    /**
     *     
     */
    @Test
    public void limitSkip(){
        DBCursor cursor = db.getCollection("movie").find(null, null);
        cursor.limit(0).skip(1);
        try{
            while(cursor.hasNext()){
                DBObject object = cursor.next();
                System.out.println("    name=" + object.get("name"));
            }
        }finally{
            cursor.close();
        }
    }
}