selectCollection() public method

Gets a collection
public selectCollection ( string $name ) : MongoCollection
$name string The collection name.
return MongoCollection Returns a new collection object.
Ejemplo n.º 1
0
 public static function getChannelCollection()
 {
     if (MongoConnector::$db == null) {
         MongoConnector::connect();
     }
     return MongoConnector::$db->selectCollection("channels");
 }
Ejemplo n.º 2
0
 /**
  * Evaluates the constraint for parameter $other. Returns TRUE if the
  * constraint is met, FALSE otherwise.
  *
  * @param mixed $other Value or object to evaluate.
  * @return bool
  */
 public function evaluate($other)
 {
     $query = array('_id' => $other);
     $data = $this->db->selectCollection($this->collection)->findOne($query);
     $this->found = $data[$this->property];
     return ($this->found == $this->expected);
 }
Ejemplo n.º 3
0
 public function getCollection($collName)
 {
     if (!$this->database) {
         throw new Exception\LogicException("Can't select collection as there's no database set");
     }
     return $this->database->selectCollection($collName);
 }
Ejemplo n.º 4
0
 public function setUp()
 {
     parent::setUp();
     $this->mongo = new MongoDB(new \MongoClient('mongodb://localhost:27017'), 'mongo_test', new InMemoryCache());
     $this->collection = $this->mongo->selectCollection('test');
     for ($i = 0; $i < 2; $i++) {
         $this->collection->insert(['foo' => 1]);
     }
 }
Ejemplo n.º 5
0
 /**
  * Retrieves a collection by name.
  * @param  $name
  * @return MongoCollection
  */
 public function collection($name)
 {
     if ($this->collections[$name]) {
         return $this->collections[$name];
     }
     $c = $this->mongo_db->selectCollection($name);
     $this->collections[$name] = $c;
     return $c;
 }
Ejemplo n.º 6
0
 /**
  * Evaluates the constraint for parameter $other. Returns TRUE if the
  * constraint is met, FALSE otherwise.
  *
  * @param mixed $other Value or object to evaluate.
  * @return bool
  */
 public function evaluate($other)
 {
     $documentExists = false;
     $query = array('_id' => $other);
     $data = $this->db->selectCollection($this->collection)->findOne($query);
     if (!empty($data)) {
         $documentExists = true;
     }
     return $documentExists;
 }
Ejemplo n.º 7
0
 /**
  */
 protected function _assocQuery($query, $filters, $parent)
 {
     foreach ($filters as $val) {
         switch ($val['op']) {
             case '>':
                 $query[$val['field']] = array('$gt' => $val['value']);
                 break;
             case '>=':
                 $query[$val['field']] = array('$gte' => $val['value']);
                 break;
             case '<':
                 $query[$val['field']] = array('$lt' => $val['value']);
                 break;
             case '<=':
                 $query[$val['field']] = array('$lte' => $val['value']);
                 break;
             case '=':
                 $query[$val['field']] = $val['value'];
                 break;
         }
     }
     if ($parent) {
         $query[self::UID] = array('$regex' => preg_quote($parent) . ':*');
     }
     try {
         $cursor = $this->_db->selectCollection(self::MONGO_DATA)->find($query, array(self::UID => true));
         $out = array();
         foreach ($cursor as $val) {
             $out[$val[self::UID]] = strval($val['_id']);
         }
     } catch (MongoException $e) {
         throw new Horde_History_Exception($e);
     }
     return $out;
 }
Ejemplo n.º 8
0
 /**
  * Imports data into the current collection
  *
  * @param string $collection
  * @param array $data
  * @param string $importMethod Valid options are batchInsert, save, insert, update
  */
 public function import($collection, array $data, $importMethod)
 {
     $coll = $this->mongo->selectCollection($collection);
     switch ($importMethod) {
         case 'batchInsert':
             foreach ($data as &$obj) {
                 $obj = unserialize($obj);
             }
             $coll->{$importMethod}($data);
             break;
         case 'update':
             foreach ($data as $obj) {
                 $obj = unserialize($obj);
                 if (is_object($obj) && property_exists($obj, '_id')) {
                     $_id = $obj->_id;
                 } else {
                     if (is_array($obj) && isset($obj['_id'])) {
                         $_id = $obj['_id'];
                     } else {
                         continue;
                     }
                 }
                 $coll->{$importMethod}(array('_id' => $_id), $obj);
             }
             break;
         default:
             //insert & save
             foreach ($data as $obj) {
                 $coll->{$importMethod}(unserialize($obj));
             }
             break;
     }
 }
Ejemplo n.º 9
0
 /**
  * Fetches the object pointed to by a reference
  * @link http://php.net/manual/en/mongodbref.get.php
  * @static
  * @param MongoDB $db Database to use
  * @param array $ref Reference to fetch
  * @return array|null Returns the document to which the reference refers or null if the document does not exist (the reference is broken)
  */
 public static function get($db, $ref)
 {
     if (!static::isRef($ref)) {
         return null;
     }
     return $db->selectCollection($ref[static::$refKey])->findOne(['_id' => $ref[static::$idKey]]);
 }
 /**
  * @access protected
  */
 protected function setUp()
 {
     $m = new Mongo();
     $db = new MongoDB($m, "phpunit");
     $this->object = $db->selectCollection('c');
     $this->object->drop();
 }
Ejemplo n.º 11
0
 /**
  * Return an array of stored tags
  *
  * @return array array of stored tags (string)
  */
 public function getTags()
 {
     $cmd['mapreduce'] = $this->_options['collection'];
     $cmd['map'] = 'function(){
                             this.t.forEach(
                                 function(z){
                                     emit( z , { count : 1 } );
                                 }
                             );
                         };';
     $cmd['reduce'] = 'function( key , values ){
                             var total = 0;
                             for ( var i=0; i<values.length; i++ )
                                 total += values[i].count;
                             return { count : total };
                         };';
     $cmd['out'] = array('replace' => 'getTagsCollection');
     $res2 = $this->_db->command($cmd);
     $res3 = $this->_db->selectCollection('getTagsCollection')->find();
     $res = array();
     foreach ($res3 as $key => $val) {
         $res[] = $key;
     }
     $this->_db->dropCollection($res2['result']);
     return $res;
 }
Ejemplo n.º 12
0
 /**
  * Gets a collection
  *
  * @link http://www.php.net/manual/en/mongocollection.get.php
  * @param string $name The next string in the collection name.
  * @return MongoCollection
  */
 public function __get($name)
 {
     // Handle w and wtimeout properties that replicate data stored in $readPreference
     if ($name === 'w' || $name === 'wtimeout') {
         return $this->getWriteConcern()[$name];
     }
     return $this->db->selectCollection($this->name . '.' . $name);
 }
Ejemplo n.º 13
0
 /**
  * Creates new file collections
  *
  * @param mongodb $db - Database.
  * @param string $prefix -
  * @param mixed $chunks -
  */
 public function __construct(MongoDB $db, $prefix = 'fs', $chunks = 'fs')
 {
     $this->db = $db;
     $thisName = $prefix . '.files';
     $this->chunksName = $prefix . '.chunks';
     $this->chunks = $db->selectCollection($this->chunksName);
     parent::__construct($db, $thisName);
 }
Ejemplo n.º 14
0
 /**
  * Purges the cache deleting all items within it.
  *
  * @return boolean True on success. False otherwise.
  */
 public function purge()
 {
     if ($this->isready) {
         $this->collection->drop();
         $this->collection = $this->database->selectCollection($this->definitionhash);
     }
     return true;
 }
Ejemplo n.º 15
0
 public function __construct(\MongoDB $db, $collection_name, array $additional_find_fields = [])
 {
     if (false === is_string($collection_name)) {
         throw new Exception('collection name must be a string');
     }
     $this->collection = $db->selectCollection($collection_name);
     $this->additional_find_fields = $additional_find_fields;
 }
Ejemplo n.º 16
0
 /**
  * @return void
  */
 public function test_function()
 {
     // prepare
     $testCollection = $this->database->selectCollection('testCollection');
     $result = iterator_to_array($testCollection->find(['_id' => 0]));
     $reflection = new \ReflectionClass(Mongo::getInstance());
     $deleteMethod = $reflection->getMethod('delete');
     $deleteMethod->setAccessible(true);
     // test
     $this->assertCount(1, $result);
     // invoke logic
     $deleteMethod->invoke(Mongo::getInstance(), 'testCollection', 1);
     // prepare
     $result = iterator_to_array($testCollection->find(['_id' => 0]));
     // test
     $this->assertCount(0, $result);
 }
Ejemplo n.º 17
0
 function doCreateIndex()
 {
     $fields = xn("field");
     if (!is_array($fields)) {
         $this->_outputJson(array("code" => 300, "message" => "Index contains one field at least."));
     }
     $orders = xn("order");
     $attrs = array();
     foreach ($fields as $index => $field) {
         $field = trim($field);
         if (!empty($field)) {
             $attrs[$field] = $orders[$index] == "asc" ? 1 : -1;
         }
     }
     if (empty($attrs)) {
         $this->_outputJson(array("code" => 300, "message" => "Index contains one field at least."));
     }
     //if is unique
     $options = array();
     if (x("is_unique")) {
         $options["unique"] = 1;
         if (x("drop_duplicate")) {
             $options["dropDups"] = 1;
         }
     }
     $options["background"] = 1;
     $options["safe"] = 1;
     //name
     $name = trim(xn("name"));
     if (!empty($name)) {
         $options["name"] = $name;
     }
     //check name
     $collection = $this->_mongodb->selectCollection($this->collection);
     $indexes = $collection->getIndexInfo();
     foreach ($indexes as $index) {
         if ($index["name"] == $name) {
             $this->_outputJson(array("code" => 300, "message" => "The name \"{$name}\" is token by other index."));
             break;
         }
         if ($attrs === $index["key"]) {
             $this->_outputJson(array("code" => 300, "message" => "The key on same fields already exists."));
             break;
         }
     }
     $ret = null;
     try {
         $ret = $collection->ensureIndex($attrs, $options);
     } catch (Exception $e) {
         $this->_outputJson(array("code" => 300, "message" => $e->getMessage()));
     }
     if ($ret["ok"]) {
         $this->_outputJson(array("code" => 200));
     } else {
         $this->_outputJson(array("code" => 300, "message" => $ret["err"]));
     }
 }
Ejemplo n.º 18
0
 /**
  * Finds one object matching the passed in query
  *
  * @param Morph_Object $object
  * @param Morph_IQuery $query
  * @return Morph_Object
  */
 public function findOneByQuery(Object $object, IQuery $query = null)
 {
     $result = null;
     $class = \get_class($object);
     $query = is_null($query) ? new Query() : $query;
     $rawQuery = $this->getRawQuery($object, $query);
     $data = $this->db->selectCollection($object->collection())->findOne($rawQuery);
     return $this->setData($object, $data);
 }
Ejemplo n.º 19
0
 public static function fields(MongoDB $db, $collection)
 {
     $one = $db->selectCollection($collection)->findOne();
     if (empty($one)) {
         return array();
     }
     $fields = array();
     self::_fieldsFromRow($fields, $one);
     return $fields;
 }
Ejemplo n.º 20
0
 /**
  * 分组获取数据
  * @param $table 集合名称
  * @param array $keys 分组字段
  * @param array $initial 分组初始条件
  * @param $reduce 分组计算方式,是一个javascript函数表达式 "function (obj, prev) { prev.items.push(obj.name); }"
  * @param $conditions 分组过滤条件
  * @param $get_all_info 是否显示所有信息
  * @return array
  */
 public function group($table, $keys, $initial, $reduce, $conditions, $get_all_info = false)
 {
     $collection = $this->db->selectCollection($table);
     $result = $collection->group($keys, $initial, $reduce, MongoQueryBuilder::where($conditions));
     if ($get_all_info) {
         return $result;
     } else {
         return $result['retval'];
     }
 }
Ejemplo n.º 21
0
 /**
  * load single record
  *
  */
 public function doRecord()
 {
     $id = rock_real_id(xn("id"));
     $format = xn("format");
     $queryFields = x("query_fields");
     $fields = array();
     if (!empty($queryFields)) {
         foreach ($queryFields as $queryField) {
             $fields[$queryField] = 1;
         }
     }
     $row = $this->_mongodb->selectCollection($this->collection)->findOne(array("_id" => $id), $fields);
     if (empty($row)) {
         $this->_outputJson(array("code" => 300, "message" => "The record has been removed."));
     }
     $exporter = new VarExportor($this->_mongodb, $row);
     $data = $exporter->export($format);
     $html = $this->_highlight($row, $format, true);
     $this->_outputJson(array("code" => 200, "data" => $data, "html" => $html));
 }
Ejemplo n.º 22
0
 public function testTest()
 {
     return;
     $mongo = new MongoDB(new \MongoClient('mongodb://localhost:27017'), 'mongo_test', new Memcache($this->memcache, 1));
     $collection = $mongo->selectCollection('test_memcache');
     $collection->insert(['foo' => 1]);
     $this->assertEquals(1, $collection->count());
     sleep(1);
     $collection->insert(['foo' => 1]);
     $this->assertEquals(2, $collection->count());
 }
Ejemplo n.º 23
0
 /**
  * Returns the object data matching the $query.
  *
  * @param \TYPO3\FLOW3\Persistence\QueryInterface $query
  * @return array
  * @author Christopher Hlubek <*****@*****.**>
  */
 public function getObjectDataByQuery(\TYPO3\FLOW3\Persistence\QueryInterface $query)
 {
     $collection = $this->database->selectCollection($this->convertClassNameToCollection($query->getType()));
     $cursor = $this->queryCollection($collection, $query);
     // TODO Use cursor properly!
     $result = iterator_to_array($cursor);
     if ($result !== NULL) {
         return $this->documentsToObjectData($result);
     } else {
         return array();
     }
 }
Ejemplo n.º 24
0
 public function testGetDBRef()
 {
     $c = $this->object->selectCollection('foo');
     $c->drop();
     for ($i = 0; $i < 50; $i++) {
         $c->insert(array('x' => rand()));
     }
     $obj = $c->findOne();
     $ref = $this->object->createDBRef('foo', $obj);
     $obj2 = $this->object->getDBRef($ref);
     $this->assertNotNull($obj2);
     $this->assertEquals($obj['x'], $obj2['x']);
 }
Ejemplo n.º 25
0
 /**
  * Runs query against the database
  *
  * The results come packages up in a Morph_Iterator object
  *
  * @param Morph_Object $object Required to determine the correct collection query against
  * @param Morph_Query $query
  * @return Morph_Iterator
  */
 public function findByQuery(Morph_Object $object, Morph_Query $query = null)
 {
     $class = get_class($object);
     $query = is_null($query) ? new Morph_Query() : $query;
     $cursor = $this->Db->selectCollection($object->collection())->find($query->getRawQuery());
     if (!is_null($query->getLimit())) {
         $results->limit($query->getLimit());
     }
     if (!is_null($query->getSkip())) {
         $results->skip($query->getSkip());
     }
     $iterator = new Morph_Iterator($object, $this, $cursor);
     return $iterator;
 }
Ejemplo n.º 26
0
 public function find(ObjectModel\Collection $collection)
 {
     $class = $collection->getDataObject()->getClass();
     $mode = $collection->getParameter('memberType');
     // set database to use
     $this->_selectDatabase($collection->getDataObject()->getUri());
     // get collection to use, from mapper if available, else from data object
     $collec = $this->_mapper instanceof Backend\Mapper ? $this->_mapper->getDatastore($class) : $class;
     $collec = $this->_db->selectCollection($collec);
     // primary key is either part of the mapper configuration or 'id'
     $pkey = $this->_mapper ? $this->_mapper->getPrimaryKey($class) : 'id';
     $conditions = array();
     /* @var $condition t41_Condition */
     foreach ($collection->getConditions() as $conditionArray) {
         $condition = $conditionArray[0];
         // map property to field
         if ($this->_mapper) {
             $field = $this->_mapper->propertyToDatastoreName($class, $condition->getProperty()->getId());
         } else {
             $field = $condition->getProperty()->getId();
         }
         $conditions += $this->_buildConditionStatement($field, $condition->getClauses(), $conditions);
         switch ($conditionArray[1]) {
             case 'OR':
                 //$select->orWhere($statement);
                 break;
             case 'AND':
             default:
                 //$select->where($statement);
                 break;
         }
     }
     //Zend_Debug::dump($conditions);
     foreach ($collection->getSortings() as $sorting) {
         if ($this->_mapper) {
             $field = $this->_mapper->propertyToDatastoreName($class, $sorting[0]->getId());
         } else {
             $field = $sorting[0]->getId();
         }
         //$select->order($field, $sorting[1]);
     }
     //		$select->limit($collection->getBatchBoundary(), $collection->getOffsetBoundary());
     $ids = $collec->find($conditions, array('_id'));
     /* prepare base of object uri */
     $uri = new ObjectModel\ObjectUri();
     $uri->setBackendUri($this->_uri);
     $uri->setClass($collection->getDataObject()->getClass());
     $uri->setUrl($this->_database . '/');
     return $this->_populateCollection(iterator_to_array($ids), $collection, $uri);
 }
Ejemplo n.º 27
0
 /**
  * Files as stored across two collections, the first containing file meta
  * information, the second containing chunks of the actual file. By default,
  * fs.files and fs.chunks are the collection names used.
  *
  * @link http://php.net/manual/en/mongogridfs.construct.php
  * @param MongoDB $db Database
  * @param string $prefix [optional] <p>Optional collection name prefix.</p>
  * @param mixed $chunks  [optional]
  * @throws \Exception
  */
 public function __construct(MongoDB $db, $prefix = "fs", $chunks = null)
 {
     if ($chunks) {
         trigger_error("The 'chunks' argument is deprecated and ignored", E_DEPRECATED);
     }
     if (empty($prefix)) {
         throw new \Exception('MongoGridFS::__construct(): invalid prefix');
     }
     $this->database = $db;
     $this->prefix = (string) $prefix;
     $this->filesName = $prefix . '.files';
     $this->chunksName = $prefix . '.chunks';
     $this->chunks = $db->selectCollection($this->chunksName);
     parent::__construct($db, $this->filesName);
 }
Ejemplo n.º 28
0
 /**
  * @param string $collectionname
  * @return boolean Whether the operation was successful
  */
 protected function _dropCollectionIfExists($collectionname)
 {
     try {
         // NOTE: the MongoCollection::dropCollection() method leaks memory, do not use
         if ($this->collectionExists($collectionname)) {
             $col = $this->dbcon->selectCollection($collectionname);
             $col->drop();
         }
         $this->numQueries++;
         return true;
     } catch (Exception $e) {
         $this->errors[] = $e->__toString() . ', caught in ' . __CLASS__ . '::' . __METHOD__ . '()';
     }
     return false;
 }
Ejemplo n.º 29
0
 /**
  * 插入新记录或者更新记录(看_id是否存在)
  * @param array $a 不传的话,插入对象自己
  */
 public function save($a = null)
 {
     $data = $a;
     if ($a == null) {
         $data = get_object_vars($this);
         unset($data['mongo'], $data['memcache'], $data['table'], $data['db'], $data['_id']);
     }
     $table = self::$db->selectCollection($this::$table);
     if ($this->_id) {
         $table->update(array("_id" => $this->_id), array('$set' => $data));
     } else {
         $table->insert($data);
         $this->_id = $data['_id'];
     }
     return $this;
 }
Ejemplo n.º 30
0
 /**
  * List collections in a DB
  *
  * @param MongoDB $db DB
  * @return array<MongoCollection>
  */
 static function listCollections(MongoDB $db)
 {
     $server = MServer::currentServer();
     $names = array();
     $query = $db->execute("function (){ return db.getCollectionNames(); }", array());
     if ($query["ok"]) {
         $names = $query["retval"];
     } else {
         $colls = $db->listCollections(true);
         foreach ($colls as $coll) {
             $names[] = $coll->getName();
         }
     }
     $ret = array();
     foreach ($names as $name) {
         if ($server->shouldHideCollection($name)) {
             continue;
         }
         if (preg_match("/^system\\./", $name)) {
             continue;
         }
         $ret[] = $name;
     }
     sort($ret);
     //system collections
     if (!$server->uiHideSystemCollections()) {
         foreach ($names as $name) {
             if ($server->shouldHideCollection($name)) {
                 continue;
             }
             if (preg_match("/^system\\./", $name)) {
                 $ret[] = $name;
             }
         }
     }
     $collections = array();
     foreach ($ret as $v) {
         if ($v === "") {
             //older MongoDB version (maybe before 1.7) allow empty collection name
             continue;
         }
         $collections[] = $db->selectCollection($v);
     }
     return $collections;
 }