标签:
鉴于开源项目的发展,大力拥抱开源社区。发现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 > 50 query = 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
标签:
原文地址:http://www.cnblogs.com/chenguanfu/p/4294205.html