相比於java調用MySqlApI來操作資料庫,調用Mongo要簡潔容易的多。通過一個簡單的樣例,很容易地就可以上手一、導入Jar包添加Monog支持Java的jar包,這裡使用的是2.9.3 org.mongodb mongo-java-driver 2.9.3二、一個簡單的樣例// 連接到...
相比於java調用MySqlApI來操作資料庫,調用Mongo要簡潔容易的多。通過一個簡單的樣例,很容易地就可以上手
一、導入Jar包
添加Monog支持Java的jar包,這裡使用的是2.9.3
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>2.9.3</version> </dependency>
二、一個簡單的樣例
// 連接到mongodb Mongo mongo = new Mongo("localhost", 27017); // 打開資料庫test DB db = mongo.getDB("test"); //獲取表,emp為表的名字,若表不存在則會自行創建 DBCollection coll = db.getCollection("emp"); //創建記錄對象,append的作用是添加屬性值 BasicDBObject doc = new BasicDBObject("name", "fzj").append("sex", "man"); //在資料庫表中添加記錄 coll.insert(doc);
三、自己寫的介面實現類(CURD)
通過上面的簡單樣例,只要接觸過資料庫和瞭解一些Mongo的語法。相信介面實現類很容易看懂
public class DBImpl implements DBTool { static DB db; static { Mongo mongo; try { mongo = new Mongo("localhost", 27017); db = mongo.getDB("test"); } catch (UnknownHostException e) { e.printStackTrace(); } } @Override public void insert(String tableName, BasicDBObject dbObject) throws UnknownHostException { DBCollection coll = db.getCollection(tableName); coll.insert(dbObject); } @Override public void delete(String tableName, BasicDBObject dbObject) throws UnknownHostException { DBCollection coll = db.getCollection(tableName); coll.remove(dbObject); } @Override public void update(String tableName, BasicDBObject docFind, BasicDBObject doc) throws UnknownHostException { DBCollection coll = db.getCollection(tableName); coll.update(docFind, doc); } @Override public DBObject find(String tableName, BasicDBObject dbObject) throws UnknownHostException { DBCollection coll = db.getCollection(tableName); return (DBObject) coll.find(); } }
參考
[1] 《mongodb-java-driver基本用法》 http://www.cnblogs.com/yjmyzz/p/3865175.html