public static void main(String[] args) { String collectionname = "test"; // MongoDB URI String uri = "mongodb://用户名:密码@ip:端口/mydatabase?authSource=mongo"; // Connect to the database using the provided URI MongoClient sourceClient = new MongoClient(new MongoClientURI(uri)); // 连接源数据库 MongoDatabase sourceDb = sourceClient.getDatabase("mongo"); MongoCollection<Document> collection = sourceDb.getCollection(collectionname); //设置查询条件 BasicDBObject query = new BasicDBObject(); // query.put("_id", new BasicDBObject("$in", Arrays.asList(1, 3, 5))); //执行查询 FindIterable<Document> documents = collection.find(query); String taruri = "mongodb://用户名:密码@ip:端口/mydatabase?authSource=mongo"; MongoClient targetClient = new MongoClient(new MongoClientURI(taruri)); // 连接目标数据库 MongoCollection<Document> targetCollection = targetClient.getDatabase("mongo_bpc").getCollection(collectionname); MongoCursor<Document> iterator = documents.iterator(); while (iterator.hasNext()) { Document document = iterator.next(); targetCollection.insertOne(document); } log.info("完成!"); // 关闭连接 sourceClient.close(); targetClient.close(); }
两个mongo数据迁移
1.不需要用户名密码时
MongoClient sourceClient = new MongoClient("ip", 端口)
MongoDatabase sourceDb = sourceClient.getDatabase("mongo");
//获取到要查询的集合(collection)
MongoCollection<Document> collection = sourceDb.getCollection(collectionname);
2.需要用户名密码
// MongoDB URI
String uri = "mongodb://用户名:密码@ip:端口/mydatabasse?authSource=mongo";
// 首先创建了一个MongoClient
对象,通过提供的MongoDB URI进行连接
MongoClient sourceClient = new MongoClient(new MongoClientURI(uri));
MongoDatabase sourceDb = sourceClient.getDatabase("mongo");
//获取到要查询的集合(collection)
MongoCollection<Document> collection = sourceDb.getCollection(collectionname);
标签:java,mongo,sourceDb,collection,sourceClient,new,迁移,MongoClient From: https://www.cnblogs.com/first131/p/17994946