레이블이 MongoDB인 게시물을 표시합니다. 모든 게시물 표시
레이블이 MongoDB인 게시물을 표시합니다. 모든 게시물 표시

2015년 7월 6일 월요일

MongoDB에서 마지막 문서 보기

1. db.collectionName.find().sort( { _id : -1 } ).limit(1);
2. db.collectionName.find({},{"_id":1}).skip(db.companies.find().count()-1);

위의 두가지가 언급되더라. 근데말이지.. 1번이 좀 더 빠른거 같더라. 
왜지? 얼핏 봤을땐 2번이 더 빠를거같은데.. 캐시 문제인가 싶어.

PS) 속도체크에는 다음의 방법을 썼다.
var before = new Date()
db.collectionName.find().sort( { _id : -1 } ).limit(1)
//db.collectionName.find({},{"_id":1}).skip(db.companies.find().count()-1)
var after = new Date()
execution_mills = after - before

2015년 7월 3일 금요일

MongoDB의 data파일을 직접 삭제한 경우.. 엿되더라.


MongoDB에서 Collection을 생성하고 Document를 생성하다보면,
DBPATH로 설정한 장소에 collection-name.ns, collection-name.{number}등의 파일들이 생성된다.

예)
> db.createCollection("people", { size: 2147483648 } )

MongoDB에 색인데이터를 정재하여 적재하는 엔진을 하나 만들어, 구동했다.
한참을 돈 후에 잘못된 부분을 발견하게 되었고 재구동을 해야만 했다.

데이터 적재 후 결과, 용량은 기억안남)
$ du -ah .
...
513M    ./people.3
129M    ./people.1
65M     ./people.0
17M     ./people.ns
...

mongo 콘솔에서 collection을 제거했다.

> db.people.drop()

헌데 데이터 파일은 사라지지 않는것이었다. 파일도 용량도 그대로.. 뭐지;?

당시 뭔생각이었는지 모르겠지만, 얼결에 MySQL 생각해서 파일을 강제삭제를 해버렸다.
(졸면서하면 이래된다. 다들알꺼다. 헐;; ㅋㅋㅋㅋㅋ)

$ rm -rf people.*
보이나? 호환마마보다 무섭다는 옵션 rf?? (배경음: 두둥~~~~~~~!!)

아무튼 깨끗해진 디랙터리는 내 정신을 정화한다. 므흣~
엔진 수정 후 구동을 실행, 어느정도 쌓였을때 다시 확인했다.
응? 뭔가 이상하다? 파일이 다른패턴으로 생성되고 있었다.

확인된 재구동 후 모습, 용량은 기억안남;ㅋ)
$ du -ah .
...
1.1G    ./people.5
1.1G    ./people.4
...

어? 뭐지? 0,1,2,3이 있었다고 4부터 생성??? 뭐??
아무튼 구동하던거 일단 내비뒀다. 데이터가 많아 2일이나 걸렸다. 젠장.

(시간여행: 2일 후)

구동완료, 일단 콘솔을 멈추고 MongoDB를 재시작했다.

> use DBNAME
> db.people.find()
>

응? 뭐지? 아무것도 안뜬다?! 인식이 안된다. 헐.. 엿됐다.
인터넷을 찾아봤다.

$ mongod --repair
변화없다. 안된다.

db.repairDatabase() //를 해보란다.
뭔가 쭉쭉 되드만.. 끝났다. 

응? 그나마 있던 파일들이 사라졌다. 헐.............. 엿x2됐다.

결국, 이 글은 2일간 뻘짓에 대한 실록.이 되어버렸다.
(아우.. 그냥 파일시스템을 직접 만들껄 왜 MongoDB를 쓰려고했을까..)

누군가 같은 경우라면 절대, 파일을 직접 삭제하지 말기를 바란다.ㅋ



2015년 6월 18일 목요일

MongoDB에서 최고값 가져오기 with C (SQL의 MAX와 동일)

최고값 구하는거때매 한참 해맸네. 뭔가 지원되겠거니 편해볼라고 기대한 내 잘못이지;;

case SQL:
SELECT MAX(sid) FROM {TABLE NAME};

case MongoDB:
 
#include <bson.h>
#include <mongoc.h>

#define MGDOID "sid"

// MongoDB에서 최고값 가져오기
unsigned long GetMaxFromMongoDB()
{
 mongoc_client_t *client;
 mongoc_collection_t *collection;
 mongoc_cursor_t *cursor;

 bson_t *pipeline;
 bson_iter_t iter;
 const bson_t *doc;
 const bson_value_t *value;

 unsigned long ans;
 
 // for debug
 clock_t cStartClock;
 cStartClock = clock();

 //mongoDB 초기화
 mongoc_init();
 client = mongoc_client_new(MONGO_SERVER);

 if (!client) {
  fprintf(stderr, "[MongoDB] Failed to parse URI.\n");
  return 0;
 }

  //MongoDB - Collection 연결
 collection = mongoc_client_get_collection (client, MONGO_DBNAME, MONGO_COLLECTION);

 pipeline = BCON_NEW ("pipeline", "[",
      "{", "$project", "{", MGDOID, BCON_INT32(1), "}", "}",
      "{", "$sort", "{", MGDOID, BCON_INT32(-1), "}", "}",
   "{", "$limit", BCON_INT32(1), "}",
   "]");

 cursor = mongoc_collection_aggregate(collection, MONGOC_QUERY_NONE, pipeline, NULL, NULL);
 
 while (mongoc_cursor_next(cursor, &doc)) {
  if(bson_iter_init(&iter, doc)) {
   while (bson_iter_next(&iter)) {
    if( strncmp(bson_iter_key(&iter), MGDOID, 3) == 0) {
     value = bson_iter_value (&iter);
//fprintf(stderr, "[%" PRId64 "]\n", value->value.v_int64);
     ans = (long)value->value.v_int64;
    }
   }
  }
 }
 bson_destroy(pipeline);

 mongoc_collection_destroy (collection);
 mongoc_client_destroy (client);
 mongoc_cleanup();

 cStartClock = (clock() - cStartClock);
 fprintf(stderr, "> GET MAX ID From MongoDB[%ld]: %2.8f sec.\n", ans, cStartClock / (double)CLOCKS_PER_SEC);

 return ans;
}


MAPPING SQL TO MONGODB (Sample)

출처: http://search.cpan.org/~mongodb/MongoDB-v0.704.5.0/lib/MongoDB/Examples.pod

MAPPING SQL TO MONGODB ^

For developers familiar with SQL, the following chart should help you see how many common SQL queries could be expressed in MongoDB.
These are Perl-specific examples of translating SQL queries to MongoDB's query language. To see the JavaScript (or other languages') mappings, seehttp://dochub.mongodb.org/core/sqlToMongo.
In the following examples, $db is a MongoDB::Database object which was retrieved by using get_database. See MongoDB::MongoClient for more.
CREATE TABLE USERS (a Number, b Number)
    Implicit, can be done explicitly.
INSERT INTO USERS VALUES(1,1)
    $db->get_collection( 'users' )->insert( { a => 1, b => 1 } );
SELECT a,b FROM users
    $db->get_collection( 'users')->find( { } )->fields( { a => 1, b => 1 });
SELECT * FROM users
    $db->get_collection( 'users' )->find;
SELECT * FROM users WHERE age=33
    $db->get_collection( 'users' )->find( { age => 33 } )
SELECT a,b FROM users WHERE age=33
    $db->get_collection( 'users' )->find( { age => 33 } )->fields( { a => 1, b => 1 });
SELECT * FROM users WHERE age=33 ORDER BY name
    $db->get_collection( 'users' )->find( { age => 33 } )->sort( { name => 1 } );
<SELECT * FROM users WHERE age33>>
    $db->get_collection( 'users' )->find( { age => { '$gt' => 33 } } );
<SELECT * FROM users WHERE age<33>
    $db->get_collection( 'users' )->find( { age => { '$lt' => 33 } } );
SELECT * FROM users WHERE name LIKE "%Joe%"
    $db->get_collection( 'users' )->find( { name => qr/Joe/ } );
SELECT * FROM users WHERE name LIKE "Joe%"
    $db->get_collection( 'users' )->find( {name => qr/^Joe/ } );
<SELECT * FROM users WHERE age33 AND age<=40>>
    $db->get_collection( 'users' )->find( { age => { '$gt' => 33, '$lte' => 40 } } );
SELECT * FROM users ORDER BY name DESC
    $db->get_collection( 'users' )->find->sort( { name => -1 } );
CREATE INDEX myindexname ON users(name)
    $db->get_collection( 'users' )->ensure_index( { name => 1 } );
CREATE INDEX myindexname ON users(name,ts DESC)
    $db->get_collection( 'users' )->ensure_index( Tie::IxHash->new( name => 1, ts => -1 ) );
In this example, we must use Tie::IxHash to preserve the ordering of the arguments to ensureIndex.
SELECT * FROM users WHERE a=1 and b='q'
    $db->get_collection( 'users' )->find( {a => 1, b => "q" } );
SELECT * FROM users LIMIT 10 SKIP 20
    $db->get_collection( 'users' )->find->limit(10)->skip(20);
SELECT * FROM users WHERE a=1 or b=2
    $db->get_collection( 'users' )->find( { '$or' => [ {a => 1 }, { b => 2 } ] } );
SELECT * FROM users LIMIT 1
    $db->get_collection( 'users' )->find->limit(1);
EXPLAIN SELECT * FROM users WHERE z=3
    $db->get_collection( 'users' )->find( { z => 3 } )->explain;
SELECT DISTINCT last_name FROM users
    $db->run_command( { distinct => "users", key => "last_name" } );
SELECT COUNT(*y) FROM users
    $db->get_collection( 'users' )->count;
<SELECT COUNT(*y) FROM users where age 30>>
    $db->get_collection( 'users' )->find( { "age" => { '$gt' => 30 } } )->count;
SELECT COUNT(age) from users
    $db->get_collection( 'users' )->find( { age => { '$exists' => 1 } } )->count;
UPDATE users SET a=1 WHERE b='q'
    $db->get_collection( 'users' )->update( { b => "q" }, { '$set' => { a => 1 } } );
UPDATE users SET a=a+2 WHERE b='q'
    $db->get_collection( 'users' )->update( { b => "q" }, { '$inc' => { a => 2 } } );
DELETE FROM users WHERE z="abc"
    $db->get_database( 'users' )->remove( { z => "abc" } );