1,下載驅動https://github.com/mongodb/mongo-java-driver/downloads,匯入工程java中
2,建立測試代碼
import java.net.UnknownHostException;
import java.util.Set;
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 TestMain {
public static void main(String[] args) throws UnknownHostException, MongoException {
// Mongo m = new Mongo();//預設本地
// Mongo m = new Mongo("192.168.0.101");//預設連接埠
Mongo m = new Mongo("192.168.0.101",27017);
//擷取名為 alan 的資料庫,不存在的情況下建立
DB db = m.getDB("alan");
//擷取所有資料庫,不顯示無collection的db
System.out.println("所有資料庫名:"+m.getDatabaseNames());
//擷取名為 testCollection 的collection(相當於表),不存在的情況下建立
DBCollection coll = db.getCollection("testCollection");
//向collection中插入值 (可以插條 )
BasicDBObject obj = new BasicDBObject();
obj.put("name","jone");
obj.put("sex", "male");
BasicDBObject info = new BasicDBObject();
info.put("height", 172);
info.put("weight", 65);
obj.put("other",info);
coll.insert(obj);
//擷取資料庫下所有的collection,不顯示無資料的collection
Set<String> colls = db.getCollectionNames();
for(String s : colls){
System.out.println(s);
}
//查詢coll中全部記錄
DBCursor ite = coll.find();
while(ite.hasNext()){
System.out.println(ite.next());
}
//擷取第一條記錄
DBObject o = coll.findOne();
System.out.println(o);
//統計colletion的資料條數
System.out.println(coll.getCount());
// 查詢 name位 mark的對象
BasicDBObject query = new BasicDBObject();
query.put("name", "mark");
DBCursor it = coll.find(query);
while(it.hasNext()){
System.out.println(it.next());
}
//查詢height小於175,weight不等於65的對象
BasicDBObject query2 = new BasicDBObject();
query2.put("other.height", new BasicDBObject("$lt", 175));
query2.put("other.weight", new BasicDBObject("$ne",65));
DBCursor it2 = coll.find(query2);
while(it2.hasNext()){
System.out.println(it2.next());
}
//更新操作
showData(coll);
BasicDBObject old_obj = new BasicDBObject();
old_obj.put("name", "mark");
//這裡的new_val對象一定要是find出的而不是new的,否則多欄位的情況下就會丟失其它欄位資訊
DBObject new_val = coll.findOne(old_obj);
new_val.put("name", "zhoulong");
/**這裡只能修改一條滿足條件的記錄,而且根據API用updateMulti方法或者設定update第四個參數也無效,
* 如果要批量跟新就要查詢後,迴圈遍曆更新了
*/
coll.update(old_obj, new_val);
showData(coll);
//刪除操作
showData(coll);
BasicDBObject rmove = new BasicDBObject();
rmove.put("name", "jone");
coll.remove(rmove);
//coll.findAndRemove(rmove);//可以用findAndRemove刪除 ,不過這個方法之能刪除一條合格記錄
showData(coll);
}
//遍曆資料
static void showData(DBCollection col)
{
DBCursor ite = col.find();
while(ite.hasNext())
{
System.out.println(ite.next());
}
}
}
3,參考api,http://api.mongodb.org/java/2.5-pre-/index.html
4,用圖形化的介面直觀看看建立的庫表和插入的資料