查询多条数据
@access public
@param array $filter
@param int $num
@param int $offset
@param array $cols 需要查询出的列
@return array
438089
public function list($filter = [], $num = 30, $offset = 0, $cols = null) {
		$query = $this->newSelect();
		if (is_array($cols)) {
			$query->addColumns(...$cols);
		}
		foreach ($filter as $k => $v) {
			$query->andWhere(field($k)->eq($v));
		}
		$query->offset($offset)->limit($num);
		return $this->execute($query);
	}
403961
private function findAndModify(array $filter, array $options)
    {
        $command = [
            'findAndModify' => $this->collectionName,
            'query' => (object) $filter,
        ];

        $options += ['typeMap' => $this->typeMap];
        $typeMap = $options['typeMap'];
        unset($options['typeMap']);

        $cursor = $this->executeCommand($command, $options);
        $result = $cursor->current();

        if (!array_key_exists('value', $result)) {
            throw new UnexpectedResultException(
                'Command "findAndModify" did not return expected "value" document.'
            );
        }

        $result = $result['value'];

        return \Tequila\MongoDB\applyTypeMap($result, $typeMap);
    }
38416
private function readFiltersAndFlags(array $options, $filter = DEFAULT_FILTER, $flags = [])
    {

        //Merge the flags
        $_flags = (isset($options['flags']) && is_array($options['flags']))
            ? array_merge($options['flags'], [])
            : $flags;

        unset($options['filters']);
        // unset($options['flags']);


        //The PHP default santize (filter) uses a defined option definition format
        // array("options"=>array(), "filters"=>array(), "flags"=>array())
        $parameters = array_merge_recursive($options, ["flags" => $_flags]);

        return [$filter, $_flags, $parameters];

    }
545912
protected function filter($type, $offset = null, $filter = FILTER_DEFAULT)
    {
        if (services()->has('xssProtection')) {
            if ( ! services()->get('xssProtection')->verify()) {
                $string = parent::filter($type, $offset, $filter);

                if (is_string($string)) {
                    return Xss::clean($string);
                }
            }
        }

        return parent::filter($type, $offset, $filter);
    }
69383
public function fetchAll($namespace, $filter = [], $options = [], $secondaryPreferred = true)
    {
        if (is_bool($secondaryPreferred)) {
            $readPreference = new ReadPreference($secondaryPreferred ? ReadPreference::RP_SECONDARY_PREFERRED : ReadPreference::RP_PRIMARY);
        } else {
            $readPreference = new ReadPreference($secondaryPreferred);
        }
        try {
            $result = $this->_fetchAll($namespace, $filter, $options, $readPreference);
        } catch (\Exception $exception) {
            $result = null;
            $failed = true;
            if (!$this->_ping()) {
                try {
                    $this->close();
                    $result = $this->_fetchAll($namespace, $filter, $options, $readPreference);
                    $failed = false;
                } catch (\Exception $exception) {
                }
            }

            if ($failed) {
                throw new MongodbException($exception->getMessage(), $exception->getCode(), $exception);
            }
        }

        return $result;
    }
565324
protected function filterLimitOffset(&$filter, $select)
    {
        $limit = null;
        $offset = null;

        if (array_key_exists('limit', $filter)) {
            $limit = (int) $filter['limit'];
            unset($filter['limit']);
        }
        if (array_key_exists('offset', $filter)) {
            $offset = (int) $filter['offset'];
            unset($filter['offset']);
        }
        $select->limit($limit, $offset);
    }
1250537
protected static function buildFilterArray($filter, $params = null)
    {
        if (empty($filter)) {
            return [];
        }

        if (is_array($filter)) {
            // assume client knows correct usage of Mongo query language
            return static::toMongoObjects($filter);
        }

        // handle logical operators first
        $logicalOperators = DbLogicalOperators::getDefinedConstants();
        foreach ($logicalOperators as $logicalOp) {
            if (DbLogicalOperators::NOT_STR === $logicalOp) {
                // NOT(a = 1)  or NOT (a = 1)format
                if ((0 === stripos($filter, $logicalOp . '(')) || (0 === stripos($filter, $logicalOp . '('))) {
                    $parts = trim(substr($filter, 3));
                    $parts = static::buildFilterArray($parts, $params);

                    return [static::localizeOperator($logicalOp) => $parts];
                }
            } else {
                // (a = 1) AND (b = 2) format
                $paddedOp = ') ' . $logicalOp . ' (';
                if (false !== $pos = stripos($filter, $paddedOp)) {
                    $left = trim(substr($filter, 0, $pos));
                    $right = trim(substr($filter, $pos + strlen($paddedOp)));
                    $left = static::buildFilterArray($left, $params);
                    $right = static::buildFilterArray($right, $params);

                    return [static::localizeOperator($logicalOp) => [$left, $right]];
                }
                // (a = 1)AND(b = 2) format
                $paddedOp = ')' . $logicalOp . '(';
                if (false !== $pos = stripos($filter, $paddedOp)) {
                    $left = trim(substr($filter, 0, $pos));
                    $right = trim(substr($filter, $pos + strlen($paddedOp)));
                    $left = static::buildFilterArray($left, $params);
                    $right = static::buildFilterArray($right, $params);

                    return [static::localizeOperator($logicalOp) => [$left, $right]];
                }
            }
        }

        $filter = trim(trim($filter, '()'));

        // the rest should be comparison operators
        // Note: order matters here!
        $sqlOperators = DbComparisonOperators::getParsingOrder();
        foreach ($sqlOperators as $sqlOp) {
            $paddedOp = static::padOperator($sqlOp);
            if (false !== $pos = stripos($filter, $paddedOp)) {
                $field = trim(substr($filter, 0, $pos));
                $negate = false;
                if (false !== strpos($field, ' ')) {
                    $parts = explode(' ', $field);
                    if ((count($parts) > 2) || (0 !== strcasecmp($parts[1], trim(DbLogicalOperators::NOT_STR)))) {
                        // invalid field side of operator
                        throw new BadRequestException('Invalid or unparsable field in filter request.');
                    }
                    $field = $parts[0];
                    $negate = true;
                }

                $value = trim(substr($filter, $pos + strlen($paddedOp)));
                if (DbComparisonOperators::requiresValueList($sqlOp)) {
                    $value = trim($value, '()[]');
                    $parsed = [];
                    foreach (explode(',', $value) as $each) {
                        $parsed[] = static::determineValue($each, $field, $params);
                    }
                    $value = $parsed;
                } elseif (DbComparisonOperators::requiresNoValue($sqlOp)) {
                    switch ($sqlOp) {
                        case DbComparisonOperators::IS_NULL:
                            return [$field => null];
                        case DbComparisonOperators::IS_NOT_NULL:
                            return [$field => ['$ne' => null]];
                        case DbComparisonOperators::DOES_EXIST:
                            return [$field => ['$exists' => true]];
                        case DbComparisonOperators::DOES_NOT_EXIST:
                            return [$field => ['$exists' => false]];
                    }
                } else {
                    $value = static::determineValue($value, $field, $params);
                    if ('$eq' === static::localizeOperator($sqlOp)) {
                        // prior to 3.0
                        if ($negate) {
                            return [$field => ['$ne' => $value]];
                        }

                        return [$field => $value];
                    } elseif (DbComparisonOperators::LIKE === $sqlOp) {
//			WHERE name LIKE "%Joe%"	(array("name" => new Regex("/Joe/")));
//			WHERE name LIKE "Joe%"	(array("name" => new Regex("/^Joe/")));
//			WHERE name LIKE "%Joe"	(array("name" => new Regex("/Joe$/")));
                        if ('%' == $value[strlen($value) - 1]) {
                            if ('%' == $value[0]) {
                                $value = trim($value, '%');
                            } else {
                                $value = '^' . rtrim($value, '%');
                            }
                        } else {
                            if ('%' == $value[0]) {
                                $value = trim($value, '%') . '$';
                            }
                        }

                        return [$field => new Regex($value, '')];
                    } elseif (DbComparisonOperators::CONTAINS === $sqlOp) {
                        return [$field => new Regex($value, '')];
                    } elseif (DbComparisonOperators::STARTS_WITH === $sqlOp) {
                        return [$field => new Regex('^' . $value, '')];
                    } elseif (DbComparisonOperators::ENDS_WITH === $sqlOp) {
                        return [$field => new Regex($value . '$', '')];
                    }
                }

                if ($negate) {
                    $value = ['$not' => $value];
                }

                return [$field => [static::localizeOperator($sqlOp) => $value]];
            }
        }

        return $filter;
    }
843865
public function findByFilter($filter, $limit = 0, $offset = 0)
    {
        $limit = $this->getLimit($limit, $offset);
        $query =
            'SELECT ' .
            $this->getFields(", ") .
            ' FROM ' .
            $this->tableName .
            ' WHERE ' .
            join(" AND ", $filter->getConditionArray()) .
            ' ' . $limit . ';';
        $statement = $this->database->prepare($query);
        $statement->execute();
        return $this->buildAll($statement->fetchAll());
    }
159145
public function setFilterColumn($cols = null)
    {
        if (!$this->model) {
            throw new Exception('Model need to be defined in order to use column filtering.');
        }

        // set filter to all column when null.
        if (!$cols) {
            foreach ($this->model->elements as $key => $field) {
                if (isset($this->columns[$key]) && $this->columns[$key]) {
                    $cols[] = $field->short_name;
                }
            }
        }

        // create column popup.
        foreach ($cols as $colName) {
            $col = $this->columns[$colName];
            if ($col) {
                $pop = $col->addPopup(new FilterPopup(['field' => $this->model->getElement($colName), 'reload' => $this->reload, 'colTrigger' => '#'.$col->name.'_ac']));
                $pop->isFilterOn() ? $col->setHeaderPopupIcon('green caret square down') : null;
                $pop->form->onSubmit(function ($f) use ($pop) {
                    return new jsReload($this->reload);
                });
                //apply condition according to popup form.
                $this->model = $pop->setFilterCondition($this->model);
            }
        }
    }
26866
public function getRawTokenAnswerRows($filter = array())
    {
        $source = $this->getSource();
        return $source->getRawTokenAnswerRows((array) $filter, $this->_surveyId, $this->_gemsSurvey['gsu_surveyor_id']);
    }
394408
public function globalFeed($filter = array(), $orderBy = 'ID DESC', $since = null, $number = 10, $markViewed = true) {
		$number = (int) $number;
		
		if (!count($filter)) {
			$filter = array('ParentID' => 0);
		}
		$filter['Deleted'] = 0;

		$items = MicroPost::get()->filter($filter)->sort($orderBy);
		
		if ($since) {
			$since = (int) $since;
			$items = $items->filter('ID:GreaterThan', $since);
		}

		if ($markViewed) {
			$this->recordUserAction();
		}
		$items = $this->updatePostList($items);
		return $items->limit($number)->restrict();
	}
285318
public function findOne(array $filter = [], array $options = [])
    {
        $documents = $this->findAll($filter, ['limit' => 1] + $options);

        return $documents->valid() ? $documents->current() : null;
    }
113792
public function set($set, $cols, $filter = null) {
		if ($filter === null) {
			$filter = &$cols;
		} else {
			//筛选$set列
			foreach ($set as $k => $v) {
				if (!in_array($k, $cols, true)) {
					unset($set[$k]);
				}
			}
		}
		$query = $this->newUpdate();
		$query->set($set);
		if ($filter !== true) {
			if (is_string($filter) || is_numeric($filter)) {
				$query->where(field($this->_primary_key)->eq($filter));
			} elseif (!is_array($filter) || count($filter) === 0) {
				throw new DBException("Filter can not be empty");
			} else {
				foreach ($filter as $k => $v) {
					$query->andWhere(field($k)->eq($v));
				}
			}
		}
		$result = $this->execute($query);
		return intval($result['_affected_rows']);
	}
4190
public function distinct($fieldName, array $filter = [], array $options = [])
    {
        if (!is_string($fieldName)) {
            throw new InvalidArgumentException('$fieldName must be a string.');
        }

        if (!$fieldName) {
            throw new InvalidArgumentException('$fieldName cannot be empty.');
        }

        $command = ['distinct' => $this->collectionName, 'key' => $fieldName];
        if ($filter) {
            $command['query'] = (object) $filter;
        }
        $options['typeMap'] = [];

        $cursor = $this->executeCommand($command, $options);

        $result = $cursor->current();
        if (!isset($result->values)) {
            throw new UnexpectedResultException(
                'Command "distinct" did not return expected "values" array.'
            );
        }

        return $result->values;
    }
1166091
public function getServices($filter = null)
	{
		$services = array();

		// Create the request
		$request = new client\Request('/api/mpegts/service/grid');

		if ($filter)
			$request->setFilter($filter);

		// Get the response
		$response = $this->_client->getResponse($request);
		$rawContent = $response->getContent();

		$content = json_decode($rawContent);

		foreach ($content->entries as $entry)
			$services[] = model\Service::fromRawEntry($entry);

		return $services;
	}
456482
function count($filter=NULL,array $options=NULL,$ttl=0) {
		$fw=\Base::instance();
		$cache=\Cache::instance();
		$tag='';
		if (is_array($ttl))
			list($ttl,$tag)=$ttl;
		if (!($cached=$cache->exists($hash=$fw->hash($fw->stringify(
			[$filter])).($tag?'.'.$tag:'').'.mongo',$result)) || !$ttl ||
			$cached[0]+$ttl<microtime(TRUE)) {
			$result=$this->collection->count($filter?:[]);
			if ($fw->CACHE && $ttl)
				// Save to cache backend
				$cache->set($hash,$result,$ttl);
		}
		return $result;
	}
52796
function  buildSqlFilter(filter, columns)  {
	if (filter.op === 'and')  {
		var  clones = [];
		filter.filters.forEach(function(f) {
			var  cf = buildSqlFilter(f, columns);
			if (cf)
				clones.push( cf );
		});
		
		var  len = clones.length;
		if (len < 1)
			return null;
		else
			return  len > 1  ?  {op: 'and', filters: clones} : clones[0];
	}
	else  if (filter.op === 'or')  {
		var  clones = [];
		filter.filters.forEach(function(f) {
			var  cf = buildSqlFilter(f, columns);
			if (cf)
				clones.push( cf );
		});

		return  clones.length === filter.filters.length  ?  {op: 'or', filters: clones} : null;
	}

	var  cf = null,
		 colName = filter.name;
	if (columns.indexOf(colName) >= 0)
		cf = filter; //cloneObj( filter );


	return  cf;
}