• Home
  • About
    • Mayaul photo

      Mayaul

      hello woooooorld.

    • Learn More
    • Facebook
    • LinkedIn
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

mongo db

04 Dec 2019

Reading time ~2 minutes

들어가며

MongoDB 에 대량의 데이터를 INSERT 를 하고 싶다면 mongoimport 사용하면 된다.
이번 Post 에서는 mongoDB 에 대량의 데이터를 일괄로 INSERT 하고 싶을때 사용하면 된다.

CSV 로 먼저 시도

mongoimport --db example --collection "test" --drop --type csv --headerline  -u "username" --file "file.csv" --authenticationDatabase "admin"
options 설명
–db example Database 이름
–collection “test” collection 이름
–drop collection 에 있는 내용을 drop 하고 저장여부
–type csv csv type
–headerline 첫번째 행이 key 값
-u “username” login 유저 이름
–file “file.csv” file 경로
–authenticationDatabase “admin” 로그인 정보가 저장이 되어있는 데이터 베이스(기본적으로 “admin” 으로 해주면 된다.

Json 으로 하자

CSV 를 이용해서 저장을 할 수 있지만, Json 의 계층구조를 저장을 할 수 없어 유용하지 않다.

mongoimport --db example --collection "test" --drop --type json --jsonArray -u "username" --file "file.json" --authenticationDatabase "admin"
옵션 설명
–db example Database 이름
–collection “test” collection 이름
–drop collection 에 있는 내용을 drop 하고 저장여부
–type json json type
–jsonArray 여러개의 json 데이터를 넣기 위해, file.json 의 구조가 array 구조일 경우
-u “username” login 유저 이름
–file “file.json” file 경로
–authenticationDatabase “admin” 로그인 정보가 저장이 되어있는 데이터 베이스(기본적으로 “admin” 으로 해주면 된다.

주의사항

-- drop 옵션의 경우 기존 데이터를 다 날리고 다시 입력을 하니, 추가적으로 데이터 입력이 필요한경우 이 옵션을 사용하지 말자

사용해보기

RDB 에 있는 여러개의 Table 의 데이터를 Join 을해서 Bulk import 가 필요한 경우 사용했던 방법

  1. CSV Import (이미 데이터베이스에 데이터가 있다면 pass)
  2. Json format 으로 쿼리 만들기
    • Intellij 에 있는 Database 에 있는 기능을 이용하면 Json 으로 데이터를 추출 할 수 있다.
    • 이외, 하위 테이블의 있는 데이터를 Json 구조로 만들었다.
       select  a,
        (select concat('{ "aa":"', t.aa, '", "bb":"', t.bb, '","location": { "x": ', t.x, ',"y":', t.y, '}}') from inner_table t where t.key = o.key) as b,
       from test o
      
    • 이렇게 해서 Intellij 에서 JSON-Groovy 로 데이터를 저장하면 된다.
  3. sub query 로 추출한 내역은 “” 으로 묶어져 있을 것이다.
    [
      {
     "a": 1,
     "b": "{ \"aa\":\"aa\", \"bb\":\"bb\",\"location\": { \"x\": 128.81864472,\"y\":35.20561835}}"
      }
    ]
    
  4. 푸는 방법
    sed -i "" "s/\\\\\"/\"/g" sample.json
    sed -i "" "s/\"{/{/g" sample.json
    sed -i "" "s/}\"/}/g" sample.json
    

    이 json 을 mongoimport 를 이용하면 된다.

    추가

    mongoimport 시에 date data type 을 지정하고 싶다면 아래와 같이 하면 된다.

    { 
      ...
      "ord_tm": {$date: "2019-11-15T22:20:42Z"}
      ...
    }
    


mongoDBimportjson Share Tweet +1