Java操作Mongo

来源:互联网 发布:在线制作纪念册 源码 编辑:程序博客网 时间:2024/05/16 02:27


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" );//获取所有CollectionSet<String> colls = db.getCollectionNames();for (String s : colls) {    System.out.println(s);}//获取特定CollectionDBCollection coll = db.getCollection("testCollection");//写入一个DocumentBasicDBObject doc = new BasicDBObject("name", "MongoDB")        .append("type", "database")        .append("count", 1)        .append("info", new BasicDBObject("x", 203).append("y", 102));coll.insert(doc);//查询一个Collection中第一个DocumentDBObject myDoc = coll.findOne();System.out.println(myDoc);//查询Collection中所有DocumentsDBCursor 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


1 0
原创粉丝点击