1. 程式人生 > >mongoDB匯出資料庫所有集合內容到json檔案

mongoDB匯出資料庫所有集合內容到json檔案

網上搜了一圈,官方並有提供批量匯出所有集合到json檔案的方法。有不少指令碼可以實現,但是我還是習慣用java,如下

package starcLL.webClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util
.regex.Pattern; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.bson.Document; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.mongodb.BasicDBObject
; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; import com.mongodb.MongoException; import com.mongodb.ServerAddress; import com.mongodb.client.ListIndexesIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase
; @Component public class MongodbClient { private static String starcLL_mongodb_ip="填寫你的ip"; private static int starcLL_mongodb_port=填寫你的埠; private static String starcLL_mongodb_name="填寫你的資料庫名"; public static MongoClient mongoClient = null; public static MongoDatabase database = null; public static ServerAddress serverAddress = null; public static MongoCredential credentials = null; public static List<ServerAddress> addressLists = new ArrayList<ServerAddress>(); public static List<MongoCredential> credentialsLists = new ArrayList<MongoCredential>(); public static MongoClient getMongoClient() { if (null == mongoClient) { try { serverAddress = new ServerAddress(starcLL_mongodb_ip, starcLL_mongodb_port); addressLists.add(serverAddress); credentials = MongoCredential.createCredential("資料庫", "使用者名稱","密碼".toCharArray()); credentialsLists.add(credentials); return new MongoClient(addressLists,credentialsLists); } catch (MongoException e) { System.out.println(e.toString()); } } return mongoClient; } public static void main(String[] args) throws IOException { MongoClient mongoClient=getMongoClient(); Set<String> collectionNames=mongoClient.getDB(starcLL_mongodb_name).getCollectionNames(); MongoDatabase mongoDatabase=mongoClient.getDatabase(starcLL_mongodb_name); System.out.println("開始..."); int i=collectionNames.size(); for (String cName:collectionNames) { JSONArray jsonArray=new JSONArray(); System.out.println("獲取集合:"+cName); MongoCursor<Document> cursor = mongoDatabase.getCollection(cName).find().iterator(); try { while (cursor.hasNext()) { jsonArray.add(cursor.next().toJson()); } } finally { cursor.close(); } File txt=new File("C:/Users/Administrator/Desktop/svc/"+i+".json"); if(!txt.exists()){ txt.createNewFile(); } byte bytes[]=new byte[512]; bytes=jsonArray.toString().getBytes(); int b=jsonArray.toString().length(); FileOutputStream fos=new FileOutputStream(txt); fos.write(bytes,0,b); fos.close(); i--; } } }