자바 조작 MongoDb 첨삭 검사

7746 단어 데이터 뱅 크
mongodb 를 어떻게 설치 하 는 지 참고 하 세 요.http://blog.csdn.net/zpf336/article/details/50765789
주:이 글 은 mongoDb API 3.2.0 을 기반 으로 한 테스트 입 니 다.
테스트 코드 는 다음 과 같 습 니 다:
pom.xml 파일

    4.0.0

    mongo
    mongodb
    0.0.1-SNAPSHOT
    jar

    mongodb
    http://maven.apache.org

    
        UTF-8
    

    
        
            junit
            junit
            4.12
            test
        
        
            org.mongodb
            mongo-java-driver
            3.2.0
        

    


MongoDb API 클래스:
package mongo.mongodb;

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

import org.bson.Document;
import org.bson.conversions.Bson;

import com.mongodb.MongoClient;
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.UpdateResult;

public class MongoDb {
    private static MongoCollection collection;

    /**
     *      
     * 
     * @param databaseName
     *                 
     * @param collectionName
     *                
     * @param hostName
     *               
     * @param port
     *               
     */
    public static void connect(String databaseName, String collectionName,
            String hostName, int port) {
        @SuppressWarnings("resource")
        MongoClient client = new MongoClient(hostName, port);
        MongoDatabase db = client.getDatabase(databaseName);
        collection = db.getCollection(collectionName);
        System.out.println(collection);
    }

    /**
     *       
     * 
     * @param document
     *              
     */
    public static void insert(Document document) {
        collection.insertOne(document);
    }

    /**
     *       
     * 
     * @return       
     */
    public static List findAll() {
        List results = new ArrayList();
        FindIterable iterables = collection.find();
        MongoCursor cursor = iterables.iterator();
        while (cursor.hasNext()) {
            results.add(cursor.next());
        }

        return results;
    }

    /**
     *       
     * 
     * @param filter
     *                 //  Bson      ,BasicDBObject, BsonDocument,
     *            BsonDocumentWrapper, CommandResult, Document, RawBsonDocument
     * @return       
     */
    public static List findBy(Bson filter) {
        List results = new ArrayList();
        FindIterable iterables = collection.find(filter);
        MongoCursor cursor = iterables.iterator();
        while (cursor.hasNext()) {
            results.add(cursor.next());
        }

        return results;
    }

    /**
     *          
     * 
     * @param filter
     *                
     * @param update
     *                
     * @return     
     */
    public static UpdateResult updateOne(Bson filter, Bson update) {
        UpdateResult result = collection.updateOne(filter, update);

        return result;
    }

    /**
     *            
     * 
     * @param filter
     *                
     * @param update
     *                
     * @return     
     */
    public static UpdateResult updateMany(Bson filter, Bson update) {
        UpdateResult result = collection.updateMany(filter, update);

        return result;
    }

    /**
     *       ,    replacement    ,        
     * 
     * @param filter
     *                
     * @param replacement
     *                
     */
    public static void replace(Bson filter, Document replacement) {
        collection.replaceOne(filter, replacement);
    }

    /**
     *           
     * 
     * @param filter
     *                
     */
    public static void deleteOne(Bson filter) {
        collection.deleteOne(filter);
    }

    /**
     *           
     * 
     * @param filter
     *                
     */
    public static void deleteMany(Bson filter) {
        collection.deleteMany(filter);
    }
}

테스트 클래스:
package mongo.mongodb;

import java.util.List;

import org.bson.Document;
import org.junit.Before;
import org.junit.Test;

import com.mongodb.client.result.UpdateResult;

public class MongoTest 
{
    @Before
    public void before(){
        MongoDb.connect("test", "darren", "172.16.155.151", 27017);
    }
    
    @Test
    public void testInsert(){
        Document document = new Document();
        document.append("name", "wang").append("gender", "female");
        MongoDb.insert(document);
    }
    
    @Test
    public void testFindAll(){
        List results = MongoDb.findAll();
        for(Document doc : results){
            System.out.println(doc.toJson());
        }
    }
    
    @Test
    public void testFindBy(){
        Document filter = new Document();
        filter.append("name", "li si");
        List results = MongoDb.findBy(filter);
        for(Document doc : results){
            System.out.println(doc.toJson());
        }
    }
    
    @Test
    public void testUpdateOne(){
        Document filter = new Document();
        filter.append("gender", "male");
        
        //  update      "$set"  
        Document update = new Document();
        update.append("$set", new Document("gender", "female"));
        UpdateResult result = MongoDb.updateOne(filter, update);
        System.out.println("matched count = " + result.getMatchedCount());
    }
    
    @Test
    public void testUpdateMany(){
        Document filter = new Document();
        filter.append("gender", "female");
        
        //  update      "$set"  
        Document update = new Document();
        update.append("$set", new Document("gender", "male"));
        UpdateResult result = MongoDb.updateMany(filter, update);
        System.out.println("matched count = " + result.getMatchedCount());
    }
    
    @Test
    public void testReplace(){
        Document filter = new Document();
        filter.append("name", "zhang");
        
        //  :     ,     "$set"
        Document replacement = new Document();
        replacement.append("value", 123);
        MongoDb.replace(filter, replacement);
    }
    
    @Test
    public void testDeleteOne(){
        Document filter = new Document();
        filter.append("name", "li");
        MongoDb.deleteOne(filter);
    }
    
    @Test
    public void testDeleteMany(){
        Document filter = new Document();
        filter.append("gender", "male");
        MongoDb.deleteMany(filter);
    }
}

공식 도움말 문서:https://docs.mongodb.org/getting-started/java/

좋은 웹페이지 즐겨찾기