Clase MongoDB
zan/classes/class.mongodb.php
Esta clase permite la creación de consultas y la manipulación de una base de datos NoSQL.
Cargando esta clase
Esta clase es cargada usando el siguiente código en los modelos:
$this->Db = $this->db("MongoDB");
Atributos
@var private $collection = NULL
@var private $condition = FALSE
@var private static $connection = FALSE
@var private $data = FALSE
@var private $fields
@var private $hint = FALSE
@var private $json = NULL
@var private $limit = FALSE
@var private $query
@var private $row
@var private $skip = FALSE
@var private $sort = array("_id" => 1)
@var private $values
__construct()
Carga el archivo de configuración de la base de datos y realiza la conexión.
collection($collection = NULL)
Inicializa el atributo $this->collection.
$this->Db->collection("mycollection");
command($command)
Sirve para ejecutar comandos directamente.
//Shut down the database $this->Db->command("shutdown");
connect()
Realiza una conexión a la base de datos.
countAll()
Cuenta todos los registros de una colección.
$this->Db->collection("mycollection"); $count = $this->Db->countAll();
countByQuery($query)
Cuenta los registros de una colección por medio de una consulta.
data()
Obtiene la información de las consultas en forma de array asociativo.
delete($criteria, $justOne = TRUE, $safe = TRUE)
Elimina un registro de una colección por medio de ciertos criterios.
public function delete($contactID = FALSE) { if($contactID) { $this->Db->collection($this->collection); $response = $this->Db->delete(array("_id" => new MongoId($contactID))); return $response; } }
deleteBy($field = FALSE, $value = FALSE, $justOne = TRUE, $safe = TRUE)
Elimina un regitro de una colección por medio de una consulta tipo Campo = Valor.
$this->Db->collection("agenda"); $this->Db->deleteBy("email", "carlos@milkzoft.com");
deleteFile($_id)
Elimina un archivo utilizando el objeto GridFS.
drop()
Elimina una colección.
$this->Db->collection("agenda"); $this->Db->drop();
$this->Db->drop("agenda");
ensureIndex($index = FALSE, $order = "ASC", $unique = FALSE)
Crea un index.
$this->Db->ensureIndex("contactID", "ASC", TRUE);
find($query = NULL, $collection = NULL, $return = TRUE)
Se encarga de ejecutar consultas y encontrar registros de una colección. Si no se le pasa una consulta obtendrá todos los registros.
$this->Db->collection("agenda"); $data = $this->Db->find();
$data = $this->Db->find(NULL, "agenda");
$this->Db->collection("agenda"); $data = $this->Db->find(array("email" => "carlos@milkzoft.com"));
$data = $this->Db->find(array("email" => "carlos@milkzoft.com"), "agenda");
findAll($collection = NULL, $group = NULL, $order = NULL, $limit = NULL)
Obtiene todos los registros de una colección.
$data = $this->Db->findAll("agenda");
$this->Db->collection("agenda"); $data = $this->Db->findAll();
findBy($field, $value, $collection = NULL)
Encuentra uno o varios registros por una consulta tipo Campo = Valor.
$data = $this->Db->findBy("email", "carlos@milkzoft.com", "agenda");
$this->Db->collection("agenda"); $data = $this->Db->findBy("email", "carlos@milkzoft.com");
findByID($ID, $collection = NULL)
Encuentra un registro por ID.
$data = $this->Db->findByID("47cc67093475061e3d95369d", "agenda");
$this->Db->collection("agenda"); $data = $this->Db->findByID("47cc67093475061e3d95369d");
findFirst()
Encuentra el primer registro de una colección.
$data = $this->Db->findFirst("agenda");
$this->Db->collection("agenda"); $data = $this->Db->findFirst();
findLast()
Encuentra el último registro de una colección.
$data = $this->Db->findLast("agenda");
$this->Db->collection("agenda"); $data = $this->Db->findLast();
get($type = "AND", $array, $return = FALSE, $add = TRUE)
Genera consultas y las convierte a formato JSon.
getAllFiles($collection = NULL)
Obtiene todos los archivos almacenados en el GridFS.
$files = $this->Db->getAllFiles("agenda");
$this->Db->collection("agenda"); $files = $this->Db->getAllFiles();
getFile($_id, $collection = NULL, $mimeType = "image/jpeg", $return = FALSE)
Obtiene un archivo específico del GridFS.
//Prints an image. $this->Db->getFile("47cc67093475061e3d95369d", "agenda");
$this->Db->collection("agenda"); //Prints an image. $this->Db->getFile("47cc67093475061e3d95369d");
//Gets an image. $image = $this->Db->getFile("47cc67093475061e3d95369d", "agenda", "image/jpeg", TRUE);
getLastID($collection = NULL)
Obtiene el ID del último registro insertado en una colección.
$lastID = $this->Db->getLastID("agenda");
$this->Db->collection("agenda"); $lastID = $this->Db->getLastID();
getNext()
Obtiene el siguiente registro dentro de un ciclo.
hint($field, $order = "ASC")
Sirve para crear un index y optimizar las consultas.
$this->Db->hint("user");
Nota: para que funcione hint(), primero debes mandar a llamar a ensureIndex().
insert($collection = NULL, $data = NULL, $_id = TRUE)
Inserta un registro en una colección.
$data = array( "name" => "Carlos", "email" => "caros@milkzoft.com", "phone" => "1234567890" ); $this->Db->insert("agenda", $data);
$this->Db->collection("agenda"); $this->Db->set("name", "Carlos"); $this->Db->set("email", "carlos@milkzoft.com"); $this->Db->set("phone", 232323); $this->Db->insert();
limit($limit = 1)
Limita el número de registros a obtener.
operator($field = NULL, $operator = "<", $value = 0, $json = FALSE)
Obtiene una consulta dependiendo del operador que se le pase.
//age < 21 $query = $this->Db->operator("age", "<", 21); //age > 21 $query = $this->Db->operator("age", ">", 21); //age <= 21 $query = $this->Db->operator("age", "<=", 21); //age >= 21 $query = $this->Db->operator("age", ">=", 21); //age != 21 / age <> 21 $query = $this->Db->operator("age", "!=", 21); $query = $this->Db->operator("age", "<>", 21); //21 in age $query = $this->Db->operator("age", "in", 21); //age = 21 or age = 22 $query = $this->Db->operator("age", "or", 21); $query = $this->Db->operator("age", "or", 22);
regex($regex, $field)
Te permite crear expresiones regulares.
$this->Db->collection("agenda"); //Here I am looking for all entry of my database wich is like "%Carlos%" and the /i param is used for Insensitive Case $data = $this->dB->regex("/^Carlos/i", "name");
rows()
Retorna el número de registros encontrados tras una consulta ejecutada.
save($option = NULL, $_id = TRUE)
Guarda un registro en una colección, es casi idéntica a insert().
$this->Db->collection("agenda"); $this->Db->set("name", "Carlos"); $this->Db->set("email", "carlos@milkzoft.com"); $this->Db->set("phone", 232323); $this->Db->save(); $this->Db->set("name", array("Hugo", "Héctor")); $this->Db->set("email", array("carlos@milkzoft.com", "ceron@milkzoft.com")); $this->Db->set("phone", array("232323", "12345")); $this->Db->save();
set($field, $value)
Inicializa valores al vector $this->data para posteriormente hacer inserciones, actualizaciones o eliminaciones.
$this->Db->set("name", "Carlos"); $this->Db->set("email", "carlos@milkzoft.com"); $this->Db->set("phone", 232323);
skip($skip = 1)
Salta u omite el número de registros específicados.
slice($field, $count = 1)
Puedes utilizar el operador slice para recuperar un subrango de los elementos de una matriz.
sort($field, $order = "ASC")
Ordena por un campo específicado ascendete o descendentemente.
update($criteria = FALSE, $update = FALSE, $options = FALSE)
Actualiza un registro dependiendo de ciertos criterios.
public function edit($contactID, $data) { $this->Db->collection($this->collection); $response = $this->Db->update(array("_id" => new MongoId($contactID)), $data); return $response; }
upload($fname = "file")
Sube un archivo al GridFS.