MongoDB를 사용할 때 collection에서 따로 _id를 지정해서 사용하지 않는다면,

ObjectId값을 이용하여 indexing되는 _id가 각 document마다 자동으로 생성된다.


이 _id를 이용하여 기간지정 query가 가능함.

MongoDB의 ObjectId의 첫 4바이트가 document 생성시간이기 때문에 가능함.


// timestamp를 넘겨받아 MongoId 객체를 생성하여 반환

function getMongoIdTimestamp($timestamp)

{

    // ObjectId는 12바이트

    // 순서는 아래와 같음

    // 4-byte : timestamp

    // 3-byte : machine identifier

    // 2-byte : product id

    // 3-byte : counter


    $_id = '';


    // timestamp (4-byte)

    $_id .= dechex($timestamp);

    // machine id (3-byte)

    $_id .= '000000';

    // product id (2-byte)

    $_id .= '0000';

    // counter (3-byte)

    $_id .= '000000';


    return new MongoId($_id);

}



// 2014년 1월 1일 자정의 timestamp

$t = strtotime(date(20140101));

// 해당 timestamp가 지정된 MongoId 객체 준비

$_id = getMongoIdTimestamp($t);


// MongoDB에 query

$m = new MongoClient(CONNECTION_STRING);

$q = array(

    '_id' => array('$gte' => $_id)

);

$cnt = $m->DB->COLLECTION->count($q);


echo date('Y-m-d', $t).' 이후의 DOCUMENT는 총 '.$cnt.' 개입니다.';





[참조]

http://docs.mongodb.org/manual/reference/object-id

http://www.php.net/mongoid.construct









Posted by bloodguy
,