【问题标题】:How can I import data to Mongodb from Json file using java如何使用 java 从 Json 文件将数据导入 Mongodb
【发布时间】:2014-12-24 18:56:39
【问题描述】:

我正在努力将数据从Json 文件导入Mongodb
我可以在命令行中使用mongoimport command 执行相同的操作。
我探索并尝试了很多,但无法使用 java 从 Json 文件中导入。

sample.json

    { "test_id" : 1245362, "name" : "ganesh", "age" : "28", "Job" : 
       {"company name" : "company1", "designation" : "SSE" } 
    }

    { "test_id" : 254152, "name" : "Alex", "age" : "26", "Job" :
       {"company name" : "company2", "designation" : "ML" } 
    }

感谢您的宝贵时间。 ~甘尼什~

【问题讨论】:

  • Java?您需要使用java driver 插入数据吗?
  • 谢谢stalk,是的,我尝试使用mongodb java驱动。 mongodb驱动不支持直接从Json文件导入数据。

标签: java json mongodb shell command-line


【解决方案1】:

假设您可以分别读取 JSON 字符串。例如,您阅读了第一个 JSON 文本

{ "test_id" : 1245362, "name" : "ganesh", "age" : "28", "Job" : 
   {"company name" : "company1", "designation" : "SSE" } 
}

并将其赋值给一个变量(String json1),下一步就是解析它,

DBObject dbo = (DBObject) com.mongodb.util.JSON.parse(json1);

将所有dbo放入一个列表中,

List<DBObject> list = new ArrayList<>();
list.add(dbo);

然后将它们保存到数据库中:

new MongoClient().getDB("test").getCollection("collection").insert(list);

编辑:

在最新的 MongoDB 版本中,您必须使用 Documents 而不是 DBObject,并且添加对象的方法现在看起来不同了。这是一个更新的示例:

进口是:

import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

代码是这样的(参考EDIT上面的文字):

Document doc = Document.parse(json1);
new MongoClient().getDataBase("db").getCollection("collection").insertOne(doc);

您也可以按照列表的方式进行操作。但是你需要

new MongoClient().getDataBase("db").getCollection("collection").insertMany(list);

但我认为这个解决方案有问题。输入时:

db.collection.find()

在mongo shell中获取集合中的所有对象,结果如下:

{ "_id" : ObjectId("56a0d2ddbc7c512984be5d97"),
    "test_id" : 1245362, "name" : "ganesh", "age" : "28", "Job" :
        { "company name" : "company1", "designation" : "SSE" 
    }
}

这和以前不太一样。

【讨论】:

    【解决方案2】:

    我自己也遇到过类似的“问题”,最终将JacksonPOJO databinding 和Morphia 一起使用。

    虽然这听起来有点像用大锤敲碎坚果,但实际上它非常易于使用、功能强大且性能非常好,并且易于维护代码。

    小警告:如果您想重用它,您需要将 test_id 字段映射到 MongoDB 的 _id

    第 1 步:创建一个带注释的 bean

    您需要提示 Jackson 如何将数据从 JSON 文件映射到 POJO。为了便于阅读,我稍微缩短了课程:

    @JsonRootName(value="person")
    @Entity
    public class Person {
    
      @JsonProperty(value="test_id")
      @Id
      Integer id;
    
      String name;
    
      public Integer getId() {
        return id;
      }
    
      public void setId(Integer id) {
        this.id = id;
      }
    
      public String getName() {
        return name;
      }
    
      public void setName(String name) {
        this.name = name;
      }
    
    }
    

    至于嵌入文档Job,请查看链接的POJO数据绑定示例。

    第 2 步:映射 POJO 并创建数据存储

    在应用程序初始化期间的某个地方,您需要映射带注释的 POJO。既然你应该已经有一个 MongoClient,我将重用它;)

    Morphia morphia = new Morphia();
    morphia.map(Person.class);
    
    /* You can reuse this datastore */
    Datastore datastore = morphia.createDatastore(mongoClient, "myDatabase");
    
    /* 
     * Jackson's ObjectMapper, which is reusable, too,
     * does all the magic.
     */
    ObjectMapper mapper = new ObjectMapper();
    

    实际导入

    现在导入给定的 JSON 文件变得如此简单

    public Boolean importJson(Datastore ds, ObjectMapper mapper, String filename) {
    
        try {           
            JsonParser parser = new JsonFactory().createParser(new FileReader(filename));
            Iterator<Person> it = mapper.readValues(parser, Person.class);
    
            while(it.hasNext()) {
                ds.save(it.next());
            }
    
            return Boolean.TRUE;
    
        } catch (JsonParseException e) {
            /* Json was invalid, deal with it here */
        } catch (JsonMappingException e) {
            /* Jackson was not able to map
             * the JSON values to the bean properties,
             * possibly because of
             * insufficient mapping information.
             */
        } catch (IOException e) {
            /* Most likely, the file was not readable
             * Should be rather thrown, but was
             * cought for the sake of showing what can happen
             */
        }
    
        return Boolean.FALSE;
    }
    

    通过一些重构,这可以在通用导入器中转换为 Jackson 注释 bean。 显然,我遗漏了一些特殊情况,但这超出了此答案的范围。

    【讨论】:

      【解决方案3】:

      使用 3.2 驱动程序,如果您有一个 mongo 集合和一个 json 文档集合,例如:

      MongoCollection<Document> collection = ...
      List<String> jsons = ...
      

      您可以单独插入:

      jsons.stream().map(Document::parse).forEach(collection::insertOne);
      

      或批量:

      collection.insertMany(
              jsons.stream().map(Document::parse).collect(Collectors.toList())
      ); 
      

      【讨论】:

      • 很好,做了类似的 ClassPathResource classPathResource = new ClassPathResource("incidents.json"); List jsons = new ArrayList(); Stream 流 = Files.lines(Paths.get(classPathResource.getFile().toURI()), StandardCharsets.UTF_8); stream.forEach(jsons::add); jsons.stream().map(Document::parse).forEach(i -> mongoTemplate.insert(i, "incidents"));
      【解决方案4】:

      运行时 r = Runtime.getRuntime();

      进程 p = null;

      //dir 是您的 mongoimport 所在的路径。

      File dir=new File("C:/Program Files/MongoDB/Server/3.2/bin");

      //这行会打开你的shell给dir,导入命令和你在命令promote中使用mongoimport完全一样

      p = r.exec("c:/windows/system32/cmd.exe /c mongoimport --db mydb --collection student --type csv --file student.csv --headerline" ,null ,dir);

      【讨论】:

        【解决方案5】:

        我今天刚刚遇到这个问题并以另一种不同的方式解决了它,而这里没有一个让我满意,所以享受我的额外贡献。性能足以导出 30k 文档并将它们导入我的 Springboot 应用程序以进行集成测试用例(需要几秒钟)。

        首先,导出数据的方式很重要。 我想要一个文件,其中每行包含一个我可以在我的 java 应用程序中解析的文档。

        mongo db --eval 'db.data.find({}).limit(30000).forEach(function(f){print(tojson(f, "", true))})' --quiet > dataset.json
        

        然后我从资源文件夹中获取文件,解析它,提取行,并使用 mongoTemplate 处理它们。可以使用缓冲区。

        @Autowired    
        private MongoTemplate mongoTemplate;
        
        public void createDataSet(){
            mongoTemplate.dropCollection("data");
            try {
                InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(DATASET_JSON);
                List<Document> documents = new ArrayList<>();
                String line;
                InputStreamReader isr = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
                BufferedReader br = new BufferedReader(isr);
                while ((line = br.readLine()) != null) {
                    documents.add(Document.parse(line));
                }
                mongoTemplate.insert(documents,"data");
        
        
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        

        【讨论】:

          【解决方案6】:
          List<Document> jsonList = new ArrayList<Document>();
          net.sf.json.JSONArray array = net.sf.json.JSONArray.fromObject(json);
          for (Object object : array) {
              net.sf.json.JSONObject jsonStr = (net.sf.json.JSONObject)JSONSerializer.toJSON(object);
              Document jsnObject = Document.parse(jsonStr.toString()); 
              jsonList.add(jsnObject);
          }
          collection.insertMany(jsonList);
          

          【讨论】:

          • 请省略仅代码答案。添加一些上下文、解释等。
          【解决方案7】:
          public static void importCSV(String path) {
          
                  try {
                      List<Document> list = new ArrayList<>();
                      MongoDatabase db = DbConnection.getDbConnection();
                      db.createCollection("newCollection");
                      MongoCollection<Document> collection = db.getCollection("newCollection");
                      BufferedReader reader = new BufferedReader(new FileReader(path));
                      String line;
                      while ((line = reader.readLine()) != null) {
                          String[] item = line.split(","); // csv file is "" separated
                          String id = item[0]; // get the value in the csv assign keywords
                          String first_name = item[1];
                          String last_name = item[2];
                          String address = item[3];
                          String gender = item[4];
                          String dob = item[5];
                          Document document = new Document(); // create a document
                          document.put("id", id); // data into the database
                          document.put("first_name", first_name);
                          document.put("last_name", last_name);
                          document.put("address", address);
                          document.put("gender", gender);
                          document.put("dob", dob);
                          list.add(document);
                      }
                      collection.insertMany(list);
          
                  }catch (Exception e){
                      System.out.println(e);
                  }
              }
          

          【讨论】:

            猜你喜欢
            • 2017-04-05
            • 2019-07-10
            • 1970-01-01
            • 2015-10-13
            • 1970-01-01
            • 2018-09-05
            • 2016-05-22
            • 2017-08-07
            • 2017-12-19
            相关资源
            最近更新 更多