MongoDB Java驅動連線基礎知識
阿新 • • 發佈:2019-02-20
Java連線 import com.mongodb.Mongo; import com.mongodb.DB; Mongo m = new Mongo(); Mongo m = new Mongo(“localhost”); Mongo m = new Mongo(“localhost”, 27017); DB db = m.getDB(“mydb”); 使用集合 從資料庫中獲取所有的集合 Set colls=db.getCollectionNames(); for(String s:colls) { System.out.println(s); } 獲取單一的集合 DBCollection coll = db.getCollection(“testCollection”); 插入文件 BasicDBObject doc = new BasicDBObject(); doc.put(“name”, “MongoDB”); doc.put(“type”, ”database”); doc.put(“count”, 1); BasicDBObject info = new BasicDBObject(); info.put(“x”, 203); info.put(“y”, 102); doc.put(“info”, info); coll.insert(doc); BasicDBObjectBuilder——編譯物件 強制轉換Maps成DBObjects,示例: BasicDBObjectBuilder.start() .add(“name”, “eliot”); .add(“number”, 17) .get(); DBObject myDoc = coll.findOne(); BasicDBObject query = new BasicDBObject(); query.put(“i”, 71); DBCursor cur = coll.find(query); GridFS 檔案大小小於4MB的儲存機制 允許部分或無序讀取塊檔案 塊結構對底層作業系統是透明的 可以在buckets儲存檔案,MongoDB metaphor 預設是fs bucket 儲存檔案到GridFS中 def mongo = new Mongo(host) def gridfs = new GridFS(mongo.getDB(”db”)) def save(inputStream, contentType, filename) { def inputFile = gridfs.createFile(inputStream); inputFile.setContentType(contentType) inputFile.setFilename(filename) inputFile.save() } 檢索/刪除檔案 def retrieveFile(String filename) { return gridfs.findOne(filename) } def deleteFile(String filename) { gridfs.remove(filename) } 2.Morphia Apache 2授權 引入了Hibernate/JPA 允許POJOs,實現MongoDB和Java之間轉換 支援DAO抽象 支援type-safe查詢 相容GWT、Guice、Spring和DI框架 Morphia註解 @Id @Entity @Embedded @Reference @Indexed @Serialized @Property 建立Morphia POJO import com.google.code.morphia.annotations.*; @Entity(“collectionName”) public class Contact{ @Id private String id; //由MongoDB產生 private String firstName; private String lastName; @Embedded Private List phoneNumbers; //getter 和 setter } 對映POJO到Mongo文件中 Morphia morphia = …; Mongo mongo = …; DB db = mongo.getDB(“contacts”); Contact contact = …; //對映contact成DBObject DBObject contactObj = morphia.toDBObject(contact); Db.getCollection(“personal”).save(contactObj); 從Mongo文件中讀取POJO Morphia morphia = …; Mongo mongo = …; DB db = mongo.getDB(“contacts”); String contactId = …; //從集合中載入物件 BasicDBObject idObj = new BasicDBObject(“_id”, new ObjectId(contactId)); BasicDBObjec obj = (BasicDBObject) db.getCollection(“personal”).findOne(idObj); Contact contact = morphia.fromDBObject(Contact.class, obj); DAOs 封裝儲存和檢索物件 POJOs進出的自動轉換 可以約束搜尋 關鍵函式:get(),find()或find(constraits),findOne(constraints),deleteById() DAO示例 import com.mongodb.Mongo import com.google.code.morphia.*; class EntryDAO extends DAO { public EntryDAO(Morphia morphia, Mongo mongo) { super(mongo, morphia, “entries”); } } 約束例子 dao.find(new Contrainst() orderByDesc(“dateCreated”) ).asList() dao.find( new Constraits() .field(“dateCreated”).greaterThanOrEqualTo(date).field(“title”). equalTo(params.title) ).asList()