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());
        }
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页