<?php $mongo = new Mongo('localhost'); $db = $mongo->test; for($i=0;$i<10000;$i++) { $a = str_repeat( str_repeat(chr(65+rand(0,25)),3), rand(1,10)); $db->towns->insert(array( 'name' => $a, 'age' => rand(1,1000) )); } $mongo->close(); ?> Более сложный запрос на выборку <?php // Триграммный поиск define('NGRAM',3); setlocale(LC_ALL,'ru_RU.UTF-8'); mb_internal_encoding("UTF-8"); $mongo = new MongoClient; $db = $mongo->test; MongoCursor::$timeout = -1; $str = 'test srting'; $len = mb_strlen($str); $len_min = $len-3; $len_max = $len+3; $search = array(); for($i=0;$i<($len-NGRAM);$i++) { $a = mb_substr($str,$i,NGRAM); if (mb_strlen($a)==NGRAM) $search[]=$a; } print_r($search); $col = $db->selectCollection("words"); $opts=array( array( '$match' => array( '$and' => array( array( 'word_len'=> array('$gt'=>$len_min)), array( 'word_len'=> array('$lt'=>$len_max)) ) )), array( '$unwind'=> '$let' ), array( '$match' => array( 'let' => array( '$in' => $search ) ) ), array( '$group' => array( '_id' => array('word_id'=>'$word_id','word'=>'$word'), 'number' => array( '$sum' =>1 ) ) ), array( '$match' => array( '$and' => array( array( 'number'=> array('$gte'=>$len_min)), array( 'number'=> array('$lte'=>$len_max)) ) )), array( '$sort' => array( 'number' => -1 ) ), array( '$limit' => 10 ) ); $results = $col->aggregate($opts); var_dump($results); $mongo->close(); ?>
PHP Справочник v0.05 © 2007-2024 Igor Salnikov aka SunDoctor