我有超过1000万个JSON文档的形式:
["key": "val2", "key1" : "val", "{\"key\":\"val", \"key2\":\"val2"}"]
Run Code Online (Sandbox Code Playgroud)
在一个文件中.
使用JAVA Driver API导入大约需要3个小时,同时使用以下功能(一次导入一个BSON):
public static void importJSONFileToDBUsingJavaDriver(String pathToFile, DB db, String collectionName) {
// open file
FileInputStream fstream = null;
try {
fstream = new FileInputStream(pathToFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("file not exist, exiting");
return;
}
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
// read it line by line
String strLine;
DBCollection newColl = db.getCollection(collectionName);
try {
while ((strLine = br.readLine()) != null) {
// convert line by line to …Run Code Online (Sandbox Code Playgroud) 在早期版本的MongoDB Java驱动程序中,要运行查询并对结果执行无序批量upsert,我们所做的就是:
BulkWriteOperation bulk = dbCollection.initializeUnorderedBulkOperation();
bulk.find(searchQuery).upsert().update(new BasicDBObject("$set", getDbObjectModel()));
Run Code Online (Sandbox Code Playgroud)
但是在版本3中,随着Bson Document支持和MongoCollection.bulkWrite()方法的引入,如何才能做到这一点?
我试过这个:
List<WriteModel<Document>> documentList = new ArrayList<>();
collection.bulkWrite(documentList, new BulkWriteOptions().ordered(false));
Run Code Online (Sandbox Code Playgroud)
但是,我需要upsert功能.
谢谢.
我需要使用Java在MongoDB上插入文档(使用特定ID代替自动生成的ObjectID)。
要插入一个文档或进行更新(如果存在),我尝试使用findOne搜索ID,如果不存在,则搜索insertID,然后选择findAndModify。它可以工作,但是我不认为这是有效的方法,很费时间。有没有更好的方法来实现这一目标?
要一次插入多个文档,我正在遵循此解决方案。但我不知道如何插入自定义ID而不是objectID?
任何帮助将不胜感激