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 表复制
猜你喜欢
转载自blog.csdn.net/u013401913/article/details/81487717
今日推荐
周排行