1. mongofiles 설치 및 운용

2. aggregate 약간의 복습

 

============================================================================

mongofiles는 4.2까지는 server를 설치할 때 같이 설치되어 있었으나 4.4부터는 빠지게 되었다.

그래서 직접 설치해줘야 함.

https://www.mongodb.com/try/download/database-tools?tck=docs_databasetools 

위의 주소에서 다운받아 설치한다.

 

설치가 잘 되었는지 확인하고 설치된 경로를 복사한다.

 

복사한 경로를 환경변수의 시스템 path에 등록한다.(많이 했으니 접속 방법은 생략)

 

윈도우 커맨드 창에서 mongofiles가 실행되는지 확인 후 실행이 되면 설치 완료

 

mongofiles

[형식]

mongofiles <options> <connection-string> <command> <filename or _id>
  - 일반적으로 mongoDB 저장할 수 있는 문서의 크기 16MB 상한
  - GridFS MongoDB를 16MB 단위로 분할해서 (입출력) 하기위한 인터페이스

 

mongofiles를 통해 db에 파일을 저장하고 해당 db에 접속하면 

fs.chunks와 fs.files collection이 생성된 것을 확인할 수 있다.

chunks collection의 각 document는 GridFS를 통해 분할된 각각의 청크들이 BSON 형식으로 저장되어있다.

files collection의 각 document는 GridFS의 파일들이다.

 

============================================================================

Q1) images 데이터베이스에 1.jpg를 올리고 싶다.
mongofiles -v -d images put 1.jpg

결과  ==> 위에서 좌->우 순서대로 명령을 실행
2021-06-15T14:48:16.465+0900    using write concern: &{majority false 0}
2021-06-15T14:48:16.486+0900    will listen for SIGTERM, SIGINT, and SIGKILL
2021-06-15T14:48:17.113+0900    connected to node type: standalone
2021-06-15T14:48:17.115+0900    connected to: mongodb://localhost/
2021-06-15T14:48:17.115+0900    handling mongofiles 'put' command...
2021-06-15T14:48:17.115+0900    adding gridFile: 1.jpg

2021-06-15T14:48:17.145+0900    creating GridFS gridFile '' from local gridFile '1.jpg'
2021-06-15T14:48:17.188+0900    copied 55476 bytes to server
2021-06-15T14:48:17.188+0900    added gridFile: 1.jpg


Q2)fs.files에 있는 파일의 목록을 확인하고 id를 찾아서 fs.chunks에서 데이터를 확인하자
ObjectId("60c83f21c779a271cff19592")
db.fs.chunks.find( {files_id : ObjectId("60c83f21c779a271cff19592") } )

show collections 하면 
fs.chunks
fs.files가 있는데 chunks에는 복사된 원본파일이 bson 타입으로 저장되어있고
files는 파일명이나 이런게 관리되고 있다

a.txt
ObjectId("60c840caca9b3786a53d8374")
db.fs.chunks.find( {files_id : ObjectId("60c840caca9b3786a53d8374") } )

c.json
ObjectId("60c8415b6e4521e1e3e9f9f2")
db.fs.chunks.find( {files_id : ObjectId("60c8415b6e4521e1e3e9f9f2") } )


Q3) 목록확인
mongofiles -v -d images list
test 폴더의 원본 지우기


Q4) d.mp4로 영상을 images db에 put한 다음 몽고 접속 후
use images로 이동해서 내용을 확인 (data는 출력x)
ObjectId("60c84e282c9e6a6a2fc00f10")
db.fs.chunks.find( { files_id : ObjectId("60c84e282c9e6a6a2fc00f10") }, { data : 0 } )

 

============================================================================

2d : 좌표 평면 계산 - 하나의 인덱스
2dsphere : 좌표, GeoJson - 위치 상관 없이 인덱스, 복합 인덱스

플레이데이터 좌표
37.486429304535626, 127.02068640002402

use geotest

var baseLng = 127.02068;
var baseLat = 37.48642;

var diffLng = 127;
var diffLat = 37;

var categories = [ '커피', '은행', '편의점' ];

for ( var i = 1; i <= 100; i++ ){
    var myLng = baseLng + ( Math.random() * diffLng );
    var myLat = baseLat + ( Math.random() * diffLat );

    var myCategories = categories[ Math.floor(Math.random() * categories.length) ];

    db.places.save( { location : [ myLng, myLat ], 
                          category : myCategories } );
};

 

============================================================================

Q1) 인덱스를 작성한다
db.places.getIndexes();
db.places.ensureIndex( { location : "2d", category : 1 } );


Q2) -180~180 범위를 벗어나는 문서를 삭제하세요
db.places.find({ location : { $gt : [180, 180] } }, {  }).count();
db.places.deleteMany( { location : { $gt : [180, 180] } } );

db.places.aggregate([
    { $match : { location : { $lte : 180 } } },
    { $count : "location" }
]);


Q3) 편의점을 찾아보자
db.places.find( { category : "편의점" } );

Q4) 은행을 찾아보자
db.places.aggregate([
    { $match : { category : "은행" } }
]);

Q5) 커피를 찾아보자
db.places.find( { category : "커피" } );


Q6) [  ] 근처에 편의점, 은행, 커피 중 가장 가까운 10개를 찾아보자
db.places.find( { location : { $near : [ 150, 50 ] } } ).limit(10);

db.places.aggregate([
    { $match : { location : { $near : [ 150, 50 ] } } },
    { $limit : 10 }
]);


Q7) 위 결과 중 가장 가까운 결과인 { "_id" : ObjectId("60c80bda3794062106b465d1"), 
     "location" : [ 147.91607640820177, 53.23275855594654 ], "category" : "은행" }에서 
     가장 가까운 5개의 편의점, 은행, 커피를 찾아보자
db.places.find( { location : { $near : [ 147.91607640820177, 53.23275855594654 ] } } ).limit(5);


Q8) 00근처에서 근방 10 거리에 있는 은행을 찾아보자.
db.places.find( { location : { $near : [ 150, 50 ], $maxDistance : 10 }, category : "은행" } );


Q9) 00근처에서 가장 멀리있는 편의점을 3개 찾아보자
db.places.find( { location : { $near : [ 150, 50 ] }, category : "편의점" } ).sort( { location : -1 } ); -- X

 

$near의 결과물은 가까운 순으로 정렬된다. sort는 가까운 순으로 정렬하지는 않는다. 즉,

db.places.find( { location : { $near : [ 150, 50 ] }, category : "편의점" } )의 결과와

db.places.find( { location : { $near : [ 150, 50 ] }, category : "편의점" } ).sort( { location : 1 } )의 결과는 같지 않다.

 

그래서

db.places.find( { location : { $near : [ 150, 50 ] }, category : "편의점" } ).sort( { location : -1 } )는 

해당 문제의 답이 아니다.

 

이 문제의 답은 고민해봐야 할 듯

 

'데이터과학자 - 강의 > javascript & mongoDB' 카테고리의 다른 글

210615 MongoDB - Replication, Sharding  (0) 2021.06.17
210615 MongoDB - mongoimport, mongoexport  (0) 2021.06.16
210614 MongoDB - aggregate  (0) 2021.06.14
210611 MongoDB  (0) 2021.06.12
210610 MongoDB  (0) 2021.06.10

+ Recent posts