相关疑难解决方法(0)

将数百万个JSON文档导入MongoDB的最快方法

我有超过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)

java import performance json mongodb

13
推荐指数
3
解决办法
2万
查看次数

使用MongoDB Java 3.0驱动程序批量Upsert

在早期版本的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 upsert mongodb mongo-java-driver

11
推荐指数
2
解决办法
1万
查看次数

MongoDB:插入具有特定ID的文档,而不是自动生成的ObjectID

我需要使用Java在MongoDB上插入文档(使用特定ID代替自动生成的ObjectID)。

  1. 要插入一个文档或进行更新(如果存在),我尝试使用findOne搜索ID,如果不存在,则搜索insertID,然后选择findAndModify。它可以工作,但是我不认为这是有效的方法,很费时间。有没有更好的方法来实现这一目标?

  2. 要一次插入多个文档,我正在遵循此解决方案。但我不知道如何插入自定义ID而不是objectID?

任何帮助将不胜感激

java mongodb

4
推荐指数
1
解决办法
9428
查看次数

标签 统计

java ×3

mongodb ×3

import ×1

json ×1

mongo-java-driver ×1

performance ×1

upsert ×1