자바 mongodb 에 대한 기본 동작 (1)

16400 단어 mongodb
최근 에 mongodb 를 사용 하려 고 합 니 다. mongodb 의 기초 조작 을 독학 하 였 습 니 다. 셸 의 핵심 조작 이 비교적 많 지만 복잡 하지 않 습 니 다. 자바 호출 은 자바 구동 패 키 징 후 더욱 간단 합 니 다. 그러나 mongodb 의 데이터 베이스 주요 기능 특성 은 분 편 된 분포 식 서비스 에 있 는 것 같 습 니 다.상위 코드:
1. 데이터베이스 연결, 생 성, 조회.
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;

public class DataBase {
    public static void main(String[] args) 
        throws UnknownHostException, MongoException {
        //1.    Mongo        
        Mongo mg = new Mongo("127.0.0.1:27017");
        //     Database
        for (String name : mg.getDatabaseNames()) {
            System.out.println("dbName: " + name);
        }
        //2.          
        DB db = mg.getDB("foobar");
        //          
        for (String name : db.getCollectionNames()) {
            System.out.println("collectionName: " + name);
        }

        DBCollection users = db.getCollection("persons");
        //       
        DBCursor cur = users.find();
        while (cur.hasNext()) {
            DBObject object = cur.next();
            System.out.println(object.get("name"));
        }
        System.out.println(cur.count());
        System.out.println(cur.getCursorId());
        System.out.println(JSON.serialize(cur));
    }
}

2. 데이터 뱅 크 의 첨삭 검사
package com.mongodb.text;

import java.net.UnknownHostException;
import java.util.List;

import org.bson.types.ObjectId;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class MongoDb {
    //1.    Mongo        
    static Mongo connection = null;
    //2.          
    static DB db = null;
    public MongoDb(String dbName) throws UnknownHostException, MongoException{
        connection = new Mongo("127.0.0.1:27017");
        db = connection.getDB(dbName);
    }
    public static void main(String[] args) throws UnknownHostException, MongoException {
        //   
        MongoDb mongoDb = new MongoDb("foobar");
        /** * 1.       javadb     */
// mongoDb.createCollection("javadb");
        /** * 2.   javadb       */
// DBObject dbs = new BasicDBObject();
// dbs.put("name", "uspcat.com");
// dbs.put("age", 2);
// List<String> books = new ArrayList<String>();
// books.add("EXTJS");
// books.add("MONGODB");
// dbs.put("books", books);
// mongoDb.insert(dbs, "javadb");
        /** * 3.       */
// List<DBObject> dbObjects = new ArrayList<DBObject>();
// DBObject jim = new BasicDBObject("name","jim");
// DBObject lisi = new BasicDBObject("name","lisi");
// dbObjects.add(jim);
// dbObjects.add(lisi);
// mongoDb.insertBatch(dbObjects, "javadb");
        /** * 4.  ID     */
// mongoDb.deleteById("502870dab9c368bf5b151a04", "javadb");
        /** * 5.         */
// DBObject lisi = new BasicDBObject();
// lisi.put("name", "lisi");
// int count = mongoDb.deleteByDbs(lisi, "javadb");
// System.out.println("        : "+count);
        /** * 6.    ,     email   */
// DBObject update = new BasicDBObject();
// update.put("$set", 
// new BasicDBObject("eamil","[email protected]"));
// mongoDb.update(new BasicDBObject(),
// update,false,true,"javadb");
        /** * 7.   persons    name age */
// DBObject keys = new BasicDBObject();
// keys.put("_id", false);
// keys.put("name", true);
// keys.put("age", true);
// DBCursor cursor = mongoDb.find(null, keys, "persons");
// while (cursor.hasNext()) {
// DBObject object = cursor.next();
// System.out.println(object.get("name"));
// }
        /** * 7.       26         80  */
// DBObject ref = new BasicDBObject();
// ref.put("age", new BasicDBObject("$gte",26));
// ref.put("e", new BasicDBObject("$lte",80));
// DBCursor cursor = mongoDb.find(ref, null, "persons");
// while (cursor.hasNext()) {
// DBObject object = cursor.next();
// System.out.print(object.get("name")+"-->");
// System.out.print(object.get("age")+"-->");
// System.out.println(object.get("e"));
// }
        /** * 8.     */
        DBCursor cursor = mongoDb.find(null, null, 0, 3, "persons");
        while (cursor.hasNext()) {
            DBObject object = cursor.next();
            System.out.print(object.get("name")+"-->");
            System.out.print(object.get("age")+"-->");
            System.out.println(object.get("e"));
        }       
        //      
        connection.close();
    }
    /** *           * @param collName      * @param db       */
    public void createCollection(String collName){
        DBObject dbs = new BasicDBObject();
        db.createCollection("javadb", dbs);
    }
    /** *            * @param dbs * @param collName */
    public void insert(DBObject dbs,String collName){
        //1.    
        DBCollection coll = db.getCollection(collName);
        //2.    
        coll.insert(dbs);
    }
    /** *           * @param dbses * @param collName */
    public void insertBatch(List<DBObject> dbses,String collName){
        //1.    
        DBCollection coll = db.getCollection(collName);
        //2.    
        coll.insert(dbses);
    }
    /** *   id     * @param id * @param collName * @return           */
    public int deleteById(String id,String collName){
        //1.    
        DBCollection coll = db.getCollection(collName);
        DBObject dbs = new BasicDBObject("_id", new ObjectId(id));
        int count = coll.remove(dbs).getN();
        return count;
    }
    /** *          * @param id * @param collName * @return           */ 
    public int deleteByDbs(DBObject dbs,String collName){
        //1.    
        DBCollection coll = db.getCollection(collName);
        int count = coll.remove(dbs).getN();
        return count;
    }
    /** *      * @param find     * @param update     * @param upsert       * @param multi        * @param collName      * @return           */
    public int update(DBObject find,
                        DBObject update,
                        boolean upsert,
                        boolean multi,
                        String collName){
        //1.    
        DBCollection coll = db.getCollection(collName);
        int count = coll.update(find, update, upsert, multi).getN();
        return count;
    }
    /** *    (  ) * @param ref * @param keys * @param start * @param limit * @return */
    public DBCursor find(DBObject ref, 
            DBObject keys,
            int start,
            int limit,
            String collName){
        DBCursor cur = find(ref, keys, collName);
        return cur.limit(limit).skip(start);
    }
    /** *    (   ) * @param ref * @param keys * @param start * @param limit * @param collName * @return */
    public DBCursor find(DBObject ref,
            DBObject keys,
            String collName){
        //1.    
        DBCollection coll = db.getCollection(collName);
        DBCursor cur = coll.find(ref, keys);
        return cur;
    }   
}






좋은 웹페이지 즐겨찾기