MongoDB & Java

摘要:MongoDB & Java

請到這

https://github.com/mongodb/mongo-java-driver/downloads

下載driver

 

引用至你的java lib

 

登入MongoDB

 

            DB db = null;
            Mongo mongo = null;
            mongo = new Mongo("localhost");
            db = mongo.getDB(database_name);
            boolean auth = db.authenticate("user", "password".toCharArray());

 

 

取得Collection

DBCollection collection = db.getCollection(collection_name);

Insert  Json

        DBObject dbObject = (DBObject) JSON.parse(json);
        collection.insert(dbObject);

update 

            BasicDBObject change = new BasicDBObject();
            change.put("_id",key);

            BasicDBObject setDoc = new BasicDBObject();
            setDoc.append("first_name", "tom");

            BasicDBObject newDoc = new BasicDBObject("$set",setDoc);
            collection.update(change,newDoc);

delete

            BasicDBObject removeObj= new BasicDBObject();
            removeObj.put("_id",key);
  
            collection.remove(removeObj);

select 

        BasicDBObject query = new BasicDBObject();
        query.put("_id",key);
        DBCursor  cur = collection.find(query);
        while(cur.hasNext())
        {
            System.out.println(cur.next());
        }