insert() публичный Метод

Inserts an array into the collection
public insert ( array | object &$a, array $options = [] ) : boolean | array
$a array | object
$options array
Результат boolean | array Returns an array containing the status of the insertion if the "w" option is set.
 /**
  * Logs a message.
  *
  * @param string $message   Message
  * @param string $priority  Message priority
  */
 protected function doLog($message, $priority)
 {
     $document = array('message' => $message, 'priority' => $priority);
     $event = new sfEvent($this, 'mongodblog.pre_insert');
     $this->dispatcher->filter($event, $document);
     $this->collection->insert($event->getReturnValue(), $this->options['save']);
 }
Пример #2
0
 /**
  */
 protected function _log($action, $message_id, $recipient, $success)
 {
     try {
         $this->_db->insert(array(self::ACTION => $action, self::MESSAGEID => $message_id, self::RECIPIENT => $recipient, self::SUCCESS => intval($success), self::TS => time(), self::WHO => $GLOBALS['registry']->getAuth()));
     } catch (MongoException $e) {
     }
 }
Пример #3
0
 /**
  * {@inheritDoc}
  */
 public function cache(BatchGeocoded $geocoded)
 {
     try {
         $this->collection->insert(array_merge(array('id' => $this->getKey($geocoded->getProviderName(), $geocoded->getQuery())), $this->normalize($geocoded)));
     } catch (\Exception $e) {
         throw new RuntimeException($e->getMessage());
     }
 }
 /**
  * Add a new Document to the DocumentStore
  * @param Document $document Document to add
  */
 public function addDocument(Document $document)
 {
     $id = new \MongoId();
     $document->_id = $id;
     $this->documents->insert($document);
     unset($document->_id);
     $this->size++;
 }
Пример #5
0
 public function testSkipCacheAggregate()
 {
     $result = $this->collection->aggregate([['$group' => ['_id' => 'foo', 'sum' => ['$sum' => '$foo']]]]);
     $this->assertEquals(4, $result['result'][0]['sum']);
     $this->collection->insert(['foo' => 3]);
     $result = $this->collection->aggregate([['$group' => ['_id' => 'foo', 'sum' => ['$sum' => '$foo']]]], ['cache' => false]);
     $this->assertEquals(7, $result['result'][0]['sum']);
 }
Пример #6
0
 /**
  * @see QueueInterface::push()
  */
 public function push(TaskInterface $task)
 {
     $eta = $task->getEta() ?: new \DateTime();
     $data = array('eta' => new \MongoDate($eta->getTimestamp()), 'task' => $this->serializer->serialize($task));
     $result = $this->collection->insert($data, array('safe' => true));
     if (!$result['ok']) {
         throw new \RuntimeException($result['errmsg']);
     }
 }
Пример #7
0
 public function save(Contact $contact)
 {
     try {
         $this->contactsManagerCollection->insert(array('name' => $contact->getName(), 'email' => $contact->getEmail(), 'photo' => $contact->getPhoto()), array('safe' => true));
         return true;
     } catch (MongoCursorException $e) {
         //log
     }
     return false;
 }
 public function testFields()
 {
     $this->object->insert(array("x" => array(1, 2, 3, 4, 5)));
     $results = $this->object->find(array(), array("x" => array('$slice' => 3)))->getNext();
     $r = $results['x'];
     $this->assertTrue(array_key_exists(0, $r));
     $this->assertTrue(array_key_exists(1, $r));
     $this->assertTrue(array_key_exists(2, $r));
     $this->assertFalse(array_key_exists(3, $r));
     $this->assertFalse(array_key_exists(4, $r));
 }
Пример #9
0
 protected function setUp()
 {
     if (!class_exists('Mongo')) {
         $this->markTestSkipped('Mongo is not installed');
     }
     $mongo = new \MongoClient();
     $this->module = new MongoDb();
     $this->module->_setConfig($this->mongoConfig);
     $this->module->_initialize();
     $this->db = $mongo->selectDB('test');
     $this->userCollection = $this->db->createCollection('users');
     $this->userCollection->insert(array('id' => 1, 'email' => '*****@*****.**'));
 }
Пример #10
0
 /**
  * @param $firstname
  * @param $lastname
  * @param $login
  * @param $password
  */
 public function add($firstname, $lastname, $login, $password, $email)
 {
     //TODO инкапсулировать в метод и обработать данные понадежнее
     //убираем лишние пробелы
     $firstname = trim($firstname);
     $lastname = trim($lastname);
     $login = trim($login);
     $password = trim($password);
     $email = trim($email);
     //формируем документ
     $document = ["firstname" => $firstname, "lastname" => $lastname, "login" => $login, "password" => $password, "email" => $email];
     //вставляем в коллекцию
     UsersCollection::$collection->insert($document);
 }
 /**
  * Appends a new event to the mongo database.
  * 
  * @throws LoggerException If the pattern conversion or the INSERT statement fails.
  */
 public function append(LoggerLoggingEvent $event)
 {
     if ($this->canAppend == true && $this->collection != null) {
         $document = $this->format($event);
         $this->collection->insert($document);
     }
 }
Пример #12
0
 /**
  * Logs a message to Mongodb
  * @param mixed $message The object to log
  * @param int $level The level of the log event
  */
 protected function log($message, $level = self::LOG_LEVEL_ERROR)
 {
     if ($message instanceof \Exception) {
         $level = self::LOG_LEVEL_EXCEPTION;
         $slog = sprintf('%s in %s [%d]', $message->getMessage(), $message->getFile(), $message->getLine());
         $trace = array();
         $stack = array_slice($message->getTrace(), 1);
         foreach ($stack as $t) {
             $trace[] = sprintf('%sin %s %s%s%s() [%d]', "\t", $t['file'], $t['class'], $t['type'] == '' ? '->' : $t['type'], $t['function'], $t['line']);
         }
         $slog .= PHP_EOL;
         $slog .= implode(PHP_EOL, $trace);
         $message = $slog;
     }
     $record = array('date' => new \MongoDate(), 'level' => static::LogLevel($level));
     if (is_scalar($message)) {
         $record['message'] = $message;
     } else {
         if (is_callable($this->serializer)) {
             $record['message'] = call_user_func_array($this->server, array($message));
         } else {
             $record['message'] = print_r($message, true);
         }
     }
     $this->collection->insert($record);
 }
Пример #13
0
 /**
  * Inserts a new object into the collection
  * 
  * @param Object $value lets you add an object to database
  */
 public function insert($value)
 {
     ValidatorsUtil::isNullOrEmpty($this->_mongoCollection, "Mongo collection isn't valid, have you set a collection?");
     ValidatorsUtil::isNull($value, "Must have a valid object to insert in collection");
     $this->_mongoCollection->insert($value, true);
     $this->_count = 0;
 }
Пример #14
0
 /**
  * Sets an item in the cache given its key and data value.
  *
  * @param string $key The key to use.
  * @param mixed $data The data to set.
  * @return bool True if the operation was a success false otherwise.
  */
 public function set($key, $data)
 {
     if (!is_array($key)) {
         $record = array('key' => $key);
     } else {
         $record = $key;
     }
     $record['data'] = serialize($data);
     $options = array('upsert' => true);
     if ($this->legacymongo) {
         $options['safe'] = $this->usesafe;
     } else {
         $options['w'] = $this->usesafe ? 1 : 0;
     }
     $this->delete($key);
     $result = $this->collection->insert($record, $options);
     if ($result === true) {
         // Safe mode is off.
         return true;
     } else {
         if (is_array($result)) {
             if (empty($result['ok']) || isset($result['err'])) {
                 return false;
             }
             return true;
         }
     }
     // Who knows?
     return false;
 }
 public function testTags() {
     // does not throw in 1.8
     try {
         $this->object->insert(array("x"=>1), array("safe" => "foo", "wtimeout" => 1000));
     }
     catch (MongoCursorException $e) {}
 }
Пример #16
0
 /**
  * Save current object to MongoDB
  *
  * @param boolean $refresh Should refresh the object fields values?
  * @return boolean
  */
 function save($refresh = false)
 {
     if (!$this->_collection) {
         import("@.RMongoException");
         throw new RMongoException("Object is not in any collection, please use setCollection() to method to set a collection.");
     }
     $bool = true;
     if ($this->_id) {
         //if exists
         if (!empty($this->_operations)) {
             $bool = $this->_collection->update(array("_id" => $this->_id), $this->_operations, array("upsert" => false, "multiple" => false));
             if ($refresh) {
                 $bool = $this->refresh();
             }
         }
     } else {
         $bool = $this->_collection->insert($this->_attrs, true);
         if ($bool) {
             $this->_id = $this->_attrs["_id"];
             import("@.RMongo");
             RMongo::setLastInsertId($this->_id->__toString());
         }
     }
     $this->_operations = array();
     return $bool;
 }
Пример #17
0
function sendMongo($steamId, $type)
{
    //function mongoConnect($steamId,$type,$collection){
    switch ($type) {
        case 1:
            //gets the player Summaries
            $fetch_pInfo = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?\t\tkey=238E8D6B70BF7499EE36312EF39F91AA&steamids={$steamId}";
            break;
        case 2:
            //gets the players Game Library
            $fetch_pInfo = "http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=238E8D6B70BF7499EE36312EF39F91AA&steamid={$steamId}&format=json";
            break;
            /*		
            			case 3://gets the players achievements
            				//steam api for players achievements.
            			break;
            			case 4://may have to get other stats,
            				//will use this maybe for players over all steam rank.
            			break;
            */
    }
    //end switch data
    $jsonO = file_get_contents($fetch_pInfo);
    var_dump($jsonO);
    $connection = new MongoClient("mongodb://*****:*****@ds041643.mongolab.com:41643/steamdata");
    $mongodb = $connection->selectDB('steamdata');
    $collection = new MongoCollection($mongodb, 'gameLibrary');
    //var_dump($connection);
    //var_dump($collection);
    $send = array();
    $send["_id"] = $steamId;
    $send["info"] = $jsonO;
    $collection->insert($send);
}
Пример #18
0
 function subscribe($identifier, $group = self::GROUP_DEFAULT)
 {
     $status = $this->getStatus($identifier);
     if ($status == self::STATUS_UNSUBSCRIBED) {
         $this->collection->insert([self::FIELD_TYPE => self::RECORD_TYPE_KEYWORD, self::FIELD_IDENTIFIER => $identifier, self::FIELD_GROUP => $group, self::FIELD_STATUS => self::STATUS_OK]);
         return true;
     } elseif ($status == self::STATUS_SUPPRESSED) {
         $this->collection->update([self::FIELD_TYPE => self::RECORD_TYPE_KEYWORD, self::FIELD_IDENTIFIER => $identifier], ['$set' => [self::FIELD_STATUS => self::STATUS_OK]], ['multiple' => false]);
         return true;
     } elseif ($status == self::STATUS_SUPPRESSING) {
         throw new \RuntimeException('Could not subscribe on identifier that currently suppressing on.');
     } elseif ($status == self::STATUS_OK) {
         return true;
     } else {
         return false;
     }
 }
Пример #19
0
 /**
  * Acquires a lock on a session, or it waits for a specified amount of time
  * WARNING: This method isn't expected to fail in any realistic application.
  * In the case of a tiny Mongo server with tons of web traffic, it's conceivable
  * that this method could fail. Keep in mind that php will
  * make sure that write() and close() is also called if this fails. There's no
  * specific way to ensure that this never fails since it's dependent on the
  * application design. Overall, one should be extremely careful with making
  * sure that the Mongo database can handle the load you'll be sending its way.
  *
  * @param  string  $sid The session ID to acquire a lock on.
  * @return boolean True if succeeded, false if not.
  */
 private function lock($sid)
 {
     //check if we've already acquired a lock
     if ($this->lockAcquired) {
         return true;
     }
     $timeout = $this->getConfig('locktimeout') * 1000000;
     //microseconds we want
     $sleep = $this->getConfig('locksleep') * 1000;
     //we want microseconds
     $start = microtime(true);
     $this->log('Trying to acquire a lock on ' . $sid);
     $waited = false;
     do {
         //check if there is a current lock
         $lock = $this->locks->findOne(array('_id' => $sid));
         if (!$lock) {
             $lock = array();
             $lock['_id'] = $sid;
             $lock['created'] = new MongoDate();
             if ($mid = $this->getConfig('machine_id')) {
                 $lock['mid'] = $mid;
             }
             try {
                 $res = $this->locks->insert($lock, $this->getConfig('write_options'));
             } catch (MongoDuplicateKeyException $e) {
                 //duplicate key may occur during lock race
                 continue;
             } catch (MongoCursorException $e) {
                 if (in_array($e->getCode(), array(11001, 11000, 12582))) {
                     //catch duplicate key if no exception thrown
                     continue;
                 } elseif (preg_match('/replication timed out/i', $e->getMessage())) {
                     //replication error, to avoid partial write/lockout override write concern and unlock before error
                     $this->instConfig['write_options'] = class_exists('MongoClient') ? array('w' => 0) : array('safe' => false);
                     //force unlock to prevent lockout from partial write
                     $this->unlock($sid, true);
                 }
                 //log exception and fail lock
                 $this->log('exception: ' . $e->getMessage());
                 break 1;
             }
             $this->lockAcquired = true;
             $this->log('Lock acquired @ ' . date('Y-m-d H:i:s', $lock['created']->sec));
             if ($waited) {
                 $this->log('LOCK_WAIT_SECONDS:' . number_format(microtime(true) - $start, 5));
             }
             return true;
         }
         //we need to sleep
         usleep($sleep);
         $waited = true;
         $timeout -= $sleep;
     } while ($timeout > 0);
     //no lock could be acquired, so try to use an error handler for this
     $this->errorHandler('Could not acquire lock for ' . $sid);
 }
Пример #20
0
 function insert($filter, $options = array())
 {
     br()->log()->writeln('MONGO->INSERT', "QRY");
     br()->log()->writeln($filter, "FLT");
     br()->log()->writeln($options, "OPT");
     $result = parent::insert($filter, $options);
     br()->log()->writeln('Query complete', 'SEP');
     return $result;
 }
Пример #21
0
 protected function doInsert(array &$a, array $options)
 {
     $document = $a;
     $result = $this->mongoCollection->insert($document, $options);
     if ($result && isset($document['_id'])) {
         $a['_id'] = $document['_id'];
     }
     return $result;
 }
Пример #22
0
 /**
  * @param $key
  * @param array $commands
  * @return bool
  */
 public function saveRequestCommands($key, array $commands)
 {
     $status = $this->commandsCollection->insert(['request_key' => $key, 'request_commands' => $commands]);
     if ($status['ok'] != 1) {
         $this->logger->error('Saving requested command failed', ['nodeName' => $this->name, 'requestKey' => $key, 'commands' => $commands, 'mongoStatus' => $status]);
         return false;
     }
     $this->logger->info('Requested commands saved', ['nodeName' => $this->name, 'requestKey' => $key, 'commands' => $commands]);
     return true;
 }
Пример #23
0
 /**
  * Add info about request in storage index.
  * It's for clients with the same requests, that can await results, but task for this request will not duplicated.
  * @param string $key Unique key for request
  * @return bool
  */
 public function addToIndex($key)
 {
     $status = $this->indexCollection->insert(['request_key' => $key]);
     if ($status['ok'] != 1) {
         $this->logger->error('Request info can not save into request index', ['nodeName' => $this->name, 'requestKey' => $key, 'mongoStatus' => $status]);
         return false;
     }
     $this->logger->info('Request info saved into request index', ['nodeName' => $this->name, 'requestKey' => $key]);
     return true;
 }
Пример #24
0
 /**
  * Insert a new record and get the value of the primary key.
  *
  * @param  array   $values
  * @param  string  $sequence
  * @return int
  */
 public function insertGetId(array $values, $sequence = null)
 {
     $result = $this->collection->insert($values);
     if (1 == (int) $result['ok']) {
         if (is_null($sequence)) {
             $sequence = '_id';
         }
         // Return id
         return $values[$sequence];
     }
 }
 public function testGetDBRef()
 {
     for ($i = 0; $i < 50; $i++) {
         $this->object->insert(array('x' => rand()));
     }
     $obj = $this->object->findOne();
     $ref = $this->object->createDBRef($obj);
     $obj2 = $this->object->getDBRef($ref);
     $this->assertNotNull($obj2);
     $this->assertEquals($obj['x'], $obj2['x']);
 }
Пример #26
0
 public function insertPost($title, $post, $tag, $date, $archieve)
 {
     $tagArray = explode(',', $tag);
     $doc = array("title" => $title, "post" => $post, "tag" => array($tagArray), "date" => new Date($date), "archieve" => $archieve);
     try {
         $col = new MongoCollection($this->con, COL_ARTICLES);
         $cur = $col->insert($doc);
     } catch (MongoCursorException $e) {
         return ADD_POST_FAILED;
     }
 }
Пример #27
0
 public function testSeeElementIsObjectThrowsError()
 {
     $trumpet = new \StdClass();
     $trumpet->name = 'Trumpet 1';
     $trumpet->pitch = 'B♭';
     $trumpet->price = array('min' => 458, 'max' => 891);
     $this->setExpectedException('PHPUnit_Framework_ExpectationFailedException');
     $this->userCollection->insert(array('id' => 5, 'trumpet' => $trumpet));
     $this->userCollection->insert(array('id' => 6, 'trumpet' => $trumpet));
     $this->module->seeElementIsObject('users', array(), 'trumpet');
 }
Пример #28
0
 function agregarATablaTemporal($TABLA, $DATOS)
 {
     try {
         $DB = $this->CONEXION->innet;
         $COLECCION = new MongoCollection($DB, "temporal" . $TABLA);
         $COLECCION->insert($DATOS);
     } catch (Exception $e) {
         $this->LOG->registraLog("Generica", $e->getMessage(), "No es posible agregar datos a la tabla temporal " . $TABLA);
         return false;
     }
     return $DATOS["_id"];
 }
Пример #29
0
 public function update()
 {
     if ($this->_collection) {
         if (is_array($this->_collection->findOne(["lid" => $this->_loc["lid"]]))) {
             return $this->_collection->update(["lid" => $this->_loc["lid"]], $this->getLoc());
         } else {
             return $this->_collection->insert($this->getLoc());
         }
     } else {
         return false;
     }
 }
Пример #30
0
 /**
  * Execute the insert query.
  *
  * @see Collection::insert()
  * @param array $a
  * @param array $options
  * @return array|boolean
  */
 protected function doInsert(array &$a, array $options)
 {
     $document = $a;
     $options = isset($options['safe']) ? $this->convertWriteConcern($options) : $options;
     $options = isset($options['wtimeout']) ? $this->convertWriteTimeout($options) : $options;
     $options = isset($options['timeout']) ? $this->convertSocketTimeout($options) : $options;
     $result = $this->mongoCollection->insert($document, $options);
     if (isset($document['_id'])) {
         $a['_id'] = $document['_id'];
     }
     return $result;
 }