本文主要是介绍Java实现mongodb 表复制,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
String tableName = "";try {// 连接到 mongodb 服务 先查询复制的那张表的数据MongoCredential credential = MongoCredential.createCredential("用户名", "数据库名", "密码".toCharArray());MongoClient mongoClient = new MongoClient(new ServerAddress("服务器IP", 端口号), Arrays.asList(credential));System.out.println("Connect to database successfully");DB database = mongoClient.getDB("数据库名");//获取数据库DBCollection collection = database.getCollection(tableName);//集合名DBCursor cursorKey = collection.find();List<DBObject> courseList = new ArrayList<DBObject>();while (cursorKey.hasNext()) {//System.out.println(cursorKey.next());courseList.add(cursorKey.next());}//复制到下面的数据库MongoCredential credential1 = MongoCredential.createCredential("用户名", "数据库名", "密码".toCharArray());MongoClient mongoClient1 = new MongoClient(new ServerAddress("IP", 端口号), Arrays.asList(credential1));System.out.println("Connect to database successfully");DB database1 = mongoClient1.getDB("数据库名");//获取数据库DBCollection collection1 = database1.getCollection(tableName);//集合名collection1.insert(courseList);// for (DBObject dbObject:courseList){// collection1.insert(dbObject);// }} catch (Exception e) {System.err.println(e.getClass().getName() + ": " + e.getMessage());}
这篇关于Java实现mongodb 表复制的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!