Java操作Mongo
简介:
<div style="margin:0px; padding:0px; border:0px; line-height:1.6; font-family:'Helvetica Neue',Arial,'Hiragino Sans GB',STHeiti,'Microsoft YaHei','WenQuanYi Micro Hei',SimSun,Song,sans-serif; font
Java操作Mongo
// 创建连接
MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017),
new ServerAddress("localhost", 27018),
new ServerAddress("localhost", 27019)));
//使用mydb数据库
DB db = mongoClient.getDB( "mydb" );
//获取所有Collection
Set<String> colls = db.getCollectionNames();
for (String s : colls) {
System.out.println(s);
}
//获取特定Collection
DBCollection coll = db.getCollection("testCollection");
//写入一个Document
BasicDBObject doc = new BasicDBObject("name", "MongoDB")
.append("type", "database")
.append("count", 1)
.append("info", new BasicDBObject("x", 203).append("y", 102));
coll.insert(doc);
//查询一个Collection中第一个Document
DBObject myDoc = coll.findOne();
System.out.println(myDoc);
//查询Collection中所有Documents
DBCursor cursor = coll.find();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
Reference
http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/#getting-started-with-java-driver