標籤:
鑒於開源項目的發展,大力擁抱開源社區。發現Java和MongoDB不失為一個較好的選擇。
與其他資料庫一樣,同樣需要mongo-java-driver,構建了Java與MongoDB的互動。
1. 串連MongoDB
1.1 普通資料庫的串連
MongoClient mongoClient = new MongoClient();
MongoClient mongoClient = new MongoClient( "localhost" );
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017),new ServerAddress("localhost", 27018),new ServerAddress("localhost", 27019)));
1.2 有許可權要求的資料庫連接
MongoCredential credential = MongoCredential.createMongoCRCredential(userName, database, password);MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential));
2. 串連MongoDB具體資料庫
2.1 串連具體資料庫
DB db = mongoClient.getDB( "mydb" );
2.2 列印所有資料庫
List<String> dbs = mongoClient.getDatabaseNames();for (String db : dbs) { System.out.println(db);}
3. 獲得資料庫中的具體一個集合
3.1 串連具體集合
DBCollection coll = db.getCollection("testCollection");
3.2 列印所有集合
Set<String> tables = db.getCollectionNames();for (String coll : tables) { System.out.println(coll);}
4. 插入資料項目
BasicDBObject doc = new BasicDBObject("name", "MongoDB") .append("type", "database") .append("count", 1) .append("info", new BasicDBObject("x", 203).append("y", 102));coll.insert(doc);
5. 查詢資料項目
5.1 查詢最新一個資料項目
DBObject myDoc = coll.findOne();System.out.println(myDoc);
5.2 查詢所有資料項目
DBCursor cursor = coll.find();try { while(cursor.hasNext()) { System.out.println(cursor.next()); }} finally { cursor.close();}
5.3 查詢資料項目個數
System.out.println(coll.getCount());
5.4 查詢特定資料項目
5.4.1 等於某個條件
BasicDBObject query = new BasicDBObject("i", 71);cursor = coll.find(query);try { while(cursor.hasNext()) { System.out.println(cursor.next()); }} finally { cursor.close();}
5.4.2 大於或者小於某個條件
// find all where i > 50query = new BasicDBObject("i", new BasicDBObject("$gt", 50));cursor = coll.find(query);try { while (cursor.hasNext()) { System.out.println(cursor.next()); }} finally { cursor.close();}
6. 更新資料項目
DBCollection table = db.getCollection("user");BasicDBObject query = new BasicDBObject();query.put("name", "mkyong");BasicDBObject newDocument = new BasicDBObject();newDocument.put("name", "mkyong-updated"); BasicDBObject updateObj = new BasicDBObject();updateObj.put("$set", newDocument); table.update(query, updateObj);
7. 刪除資料項目
DBCollection table = db.getCollection("user");BasicDBObject searchQuery = new BasicDBObject();searchQuery.put("name", "mkyong"); table.remove(searchQuery);
Java and MongoDB link for project