/** * Page Dashboard. */ public function dashboard() { $nbacteurs = Actors::count(); $nbcommentaires = Comments::count(); $nbmovies = Movies::count(); $nbseances = Sessions::count(); $manager = new \MongoDB\Driver\Manager('mongodb://localhost:27017'); $collection = new \MongoDB\Collection($manager, 'laravel', 'videos'); $videos = collect($collection->find()->toArray())->shuffle(); $collection = new \MongoDB\Collection($manager, 'laravel', 'stats'); $youtubeinfo = collect($collection->find(['origin' => 'Youtube'])->toArray())->first(); $collection = new \MongoDB\Collection($manager, 'laravel', 'stats'); $tweeterinfo = collect($collection->find(['origin' => 'Twitter', 'type' => 'infos'])->toArray())->first(); $actor = new Actors(); // Je récpere mon modèle $comment = new Comments(); // Je récpere mon modèle $movie = new Movies(); // Je récpere mon modèle $session = new Sessions(); // Je récpere mon modèle $user = new User(); // Je récpere mon modèle $avgacteurs = $actor->getAvgActors(); $avgnotecommentaire = $comment->getAvgNote(); $avgnotepresse = $movie->getAvgNotePresse(); $avghour = $session->getAvgHourDate(); $seances = $session->getNextSession(); $users = $user->getLastUsers(); return view('Main/dashboard', ['avgnotecommentaire' => $avgnotecommentaire->avgnote, 'avgnotepresse' => $avgnotepresse->avgpress, 'avgacteurs' => $avgacteurs->age, 'videos' => $videos, 'video' => $videos[0], 'youtubeinfo' => $youtubeinfo->data, 'tweeterinfo' => $tweeterinfo['data'][0], 'youtubeinfodateupdated' => $youtubeinfo->created, 'tweeterinfodateupdated' => $tweeterinfo['created_at'], 'avghour' => $avghour->avghour, 'nbacteurs' => $nbacteurs, 'nbcommentaires' => $nbcommentaires, 'nbmovies' => $nbmovies, 'nbseances' => $nbseances, 'seances' => $seances, 'users' => $users]); }
/** * Execute the console command. * * @return mixed */ public function handle() { $keyword = $this->argument('keyword'); $channel = Yt::getChannelByName('allocine'); if (!empty($channel)) { $manager = new \MongoDB\Driver\Manager('mongodb://localhost:27017'); $collection = new \MongoDB\Collection($manager, 'laravel.stats'); $collection->deleteMany([]); $collection = new \MongoDB\Collection($manager, 'laravel.stats'); $stat = ['origin' => 'Youtube', 'type' => 'search', 'data' => $channel, 'created' => new \MongoDB\BSON\UTCDatetime(time())]; $collection->insertOne($stat); } $params = ['q' => $keyword, 'type' => 'video', 'part' => 'id, snippet', 'maxResults' => 30]; $videos = Yt::searchAdvanced($params, true)['results']; if (!empty($videos)) { $collection = new \MongoDB\Collection($manager, 'laravel.videos'); $collection->deleteMany([]); foreach ($videos as $video) { $collection = new \MongoDB\Collection($manager, 'laravel.videos'); $stat = ['data' => $video, 'created' => new \MongoDB\BSON\UTCDatetime(time())]; $collection->insertOne($stat); } } Log::info("Import de l'API Youtube video done! "); }
/** * {@inheritdoc } */ public function set($key, $value, $ttl = null) { $tKey = $this->getKey($key); $tValue = $this->pack($value); if (!$ttl) { $ttl = $this->ttl; } $item = array('_id' => $tKey, 'value' => $tValue, 'ttl' => $this->getTtl($ttl)); $this->collection->update(array('_id' => $tKey), $item, array('upsert' => true)); }
/** * Test Api for Create Account. */ public function testCreateAccount() { $data = ["name" => "Test", "cp" => 75001, "phone" => "0601010101", "sexe" => 1, "news" => true, "email" => "*****@*****.**"]; $this->post('/api/createaccount', $data)->seeJson(['state' => true])->assertResponseOk(); $this->post('/api/createaccount', $data)->seeJson(['state' => false]); $manager = new \MongoDB\Driver\Manager('mongodb://localhost:27017'); $collection = new \MongoDB\Collection($manager, 'builders', 'account'); $one = $collection->findOneAndDelete(["email" => $data["email"]]); $this->assertEquals($one->email, $data["email"]); }
/** * List ads */ public function ads() { $manager = new \MongoDB\Driver\Manager('mongodb://localhost:27017'); $collection = new \MongoDB\Collection($manager, 'builders', 'ads'); $result = $collection->find()->toArray(); $tab = []; foreach ($result as $one) { $tab[] = $one->bsonSerialize(); } return response()->json($tab); }
/** * @param string $user_email * * @return HHPnet\Core\Domain\Users\User */ public function getByEmail($user_email) { $user = $this->collection->findOne(['email' => $user_email]); return $this->getUserInstance($user); }
/** * -------------------------------------------------------------------------------- * // Get * -------------------------------------------------------------------------------- * * Get the documents based upon the passed parameters * * @usage : $this->mongo_db->get('foo'); */ public function get($collection = "") { if (empty($collection)) { show_error("In order to retrieve documents from MongoDB, a collection name must be passed", 500); } try { $options = ['limit' => (int) $this->limit, 'skip' => (int) $this->offset, 'sort' => $this->sorts, 'batchSize' => (int) $this->limit, 'cursorType' => 2, ['projection' => $this->selects]]; $collection = new MongoDB\Collection($this->connect, $this->config[$this->activate]['database'] . "." . $collection); //$this->db->selectCollection($collection); $documents = $collection->find($this->wheres, $options); $this->explain($documents, $collection); // Clear $this->_clear(); $returns = $documents->toArray(); if ($this->return_as == 'object') { return (object) $returns; } else { return $returns; } } catch (MongoDB\Driver\Exception\BulkWriteException $e) { if (isset($this->debug) == TRUE && $this->debug == TRUE) { show_error("MongoDB query failed: {$e->getMessage()}", 500); } else { show_error("MongoDB query failed.", 500); } } }
<?php require_once __DIR__ . "/bootstrap.php"; $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017"); $collection = new MongoDB\Collection($manager, "phplib_demo.bulkwrite"); function dumpWriteResults(MongoDB\BulkWriteResult $result) { printf("Inserted %d documents, upserted %d, updated %d, and deleted %d\n", $result->getInsertedCount(), $result->getUpsertedCount(), $result->getModifiedCount(), $result->getDeletedCount()); if ($result->getUpsertedCount()) { foreach ($result->getUpsertedIds() as $index => $id) { printf("upsertedId[%d]: %s\n", $index, $id); } } } function dumpCollection($collection) { printf("Dumping all documents in: %s.%s\n", $collection->getDatabaseName(), $collection->getCollectionName()); $n = 0; foreach ($collection->find() as $document) { var_dump($document); $n++; } printf("Found %d documents\n", $n); } $result = $collection->bulkWrite([["insertOne" => [["name" => "Hannes Magnusson", "company" => "10gen"]]], ["insertOne" => [["name" => "Jeremy Mikola", "company" => "10gen"]]], ["updateMany" => [["company" => "10gen"], ['$set' => ["company" => "MongoDB"]]]], ["updateOne" => [["name" => "Hannes Magnusson"], ['$set' => ["viking" => true]]]]]); dumpWriteResults($result); echo "\n"; dumpCollection($collection); echo "\n"; $result = $collection->bulkWrite([["deleteOne" => [["company" => "MongoDB"]]], ["updateOne" => [["name" => "Hannes Magnusson"], ['$set' => ["nationality" => "Icelandic"]], ["upsert" => true]]], ["deleteMany" => [["nationality" => ['$ne' => "Icelandic"]]]]]); dumpWriteResults($result);
/** * Update account */ public function updateAccount(Request $request) { $data = ["name" => $request->name, "cp" => $request->cp, "phone" => $request->phone, "sexe" => $request->sexe, "news" => $request->news]; $manager = new \MongoDB\Driver\Manager('mongodb://localhost:27017'); $collection = new \MongoDB\Collection($manager, 'builders', 'account'); $stat = ['email' => $request->email, 'data' => $data, 'created' => new \DateTime("now")]; try { $collection->updateOne(["email" => $request->email], $stat); } catch (\Exception $e) { return response()->json(['state' => false]); } $data["email"] = $request->email; return response()->json(['data' => $data, 'state' => true]); }
/** * Execute the console command. * * @return mixed */ public function handle() { $infos = \Thujohn\Twitter\Facades\Twitter::getUsersLookup(['screen_name' => 'Symfomany', 'format' => 'php']); $manager = new \MongoDB\Driver\Manager('mongodb://localhost:27017'); $collection = new \MongoDB\Collection($manager, 'laravel.tweets'); if (!empty($infos)) { $collection->deleteMany(['origin' => 'Twitter', 'type' => 'infos']); $stat = ['origin' => 'Twitter', 'type' => 'infos', 'data' => $infos, 'created' => new \MongoDB\BSON\UTCDatetime(time())]; $collection->insertOne($stat); } $tweets = \Thujohn\Twitter\Facades\Twitter::getDmsOut(['format' => 'php']); if (!empty($tweets)) { $collection->deleteMany(['origin' => 'Twitter', 'type' => 'dmsout']); foreach ($tweets as $tweet) { $stat = ['origin' => 'Twitter', 'type' => 'dmsout', 'data' => $tweet, 'created' => new \MongoDB\BSON\UTCDatetime(time())]; $collection->insertOne($stat); } } $tweets = \Thujohn\Twitter\Facades\Twitter::getFavorites(['format' => 'php']); if (!empty($tweets)) { $collection->deleteMany(['origin' => 'Twitter', 'type' => 'favorites']); foreach ($tweets as $tweet) { $stat = ['origin' => 'Twitter', 'type' => 'favorites', 'data' => $tweet, 'created' => new \MongoDB\BSON\UTCDatetime(time())]; $collection->insertOne($stat); } } $tweets = \Thujohn\Twitter\Facades\Twitter::getMentionsTimeline(['count' => 15, 'format' => 'php']); if (!empty($tweets)) { $collection->deleteMany(['origin' => 'Twitter', 'type' => 'mentionstimeline']); foreach ($tweets as $tweet) { $stat = ['origin' => 'Twitter', 'type' => 'mentionstimeline', 'data' => $tweet, 'created' => new \MongoDB\BSON\UTCDatetime(time())]; $collection->insertOne($stat); } } $tweets = \Thujohn\Twitter\Facades\Twitter::getHomeTimeline(['count' => 15, 'format' => 'php']); if (!empty($tweets)) { $collection->deleteMany(['origin' => 'Twitter', 'type' => 'hometimeline']); foreach ($tweets as $tweet) { $stat = ['origin' => 'Twitter', 'type' => 'hometimeline', 'data' => $tweet, 'created' => new \MongoDB\BSON\UTCDatetime(time())]; $collection->insertOne($stat); } } $tweets = \Thujohn\Twitter\Facades\Twitter::getUserTimeline(['screen_name' => 'allocine', 'count' => 15, 'format' => 'php']); if (!empty($tweets)) { $collection->deleteMany(['origin' => 'Twitter', 'type' => 'usertimeline']); foreach ($tweets as $tweet) { $stat = ['origin' => 'Twitter', 'type' => 'usertimeline', 'data' => $tweet, 'created' => new \MongoDB\BSON\UTCDatetime(time())]; $collection->insertOne($stat); } } }
/** * @param string $video_service_id * @param string $video_service * * @return HHPnet\Core\Domain\Videos\Video */ public function getByVideoServiceId($video_service_id, $video_service) { $video = $this->collection->findOne(['video_service_id' => $video_service_id, 'video_service' => $video_service]); return $this->getVideoInstance($video); }
/** * @param string $name * * @return HHPnet\Core\Domain\Groups\Group */ public function getByGroupByName($name) { $group = $this->collection->findOne(['name' => $name]); return $this->getGroupInstance($group); }
/** * @param HHPnet\Core\Domain\Groups\GroupId $group_id * @param string $name * * @return HHPnet\Core\Domain\Albums\Album */ public function getAlbumByName(GroupId $group_id, $name) { $album = $this->collection->findOne(['group_id' => $group_id, 'name' => $name]); return $this->getAlbumInstance($album); }
<?php try { // included for debugging purposes - should be removed in any production code ini_set('display_errors', 1); date_default_timezone_set("UTC"); // include the mongodb library require 'vendor/autoload.php'; // connect to the database. replace "mongo-example.continental" with where you imported the sample dataset $manager = new MongoDB\Driver\Manager("mongodb://*****:*****@10.99.0.78:27017/mongo-example"); $collection = new MongoDB\Collection($manager, "mongo-example.continental"); //filter - conditions to limit search results $filter = null; //limit - optional limit for aggregation results $limit = 10000; //put_id - whether to add ID to values or not. $put_id = true; //id - id of requested top section. Like name of continent - "Europe" in this example. $id = ""; $sort_field = "sum"; //group_field - field for aggregation grouping, by defult at first we want results grouped by "continent". $group_field = "continent"; //Case if section id is passed along request. This is where we read our //custom made ID and then understand if this is first level of drilldown or //second one. Based on the level of drilldown we set group_field and other //parameters as needed. if (isset($_GET["id"]) && $_GET["id"]) { $id = $_GET["id"]; $parts = explode("_", $id); $c = count($parts); if ($c == 1) {
/** * @param HHPnet\Core\Domain\Albums\AlbumId $song_id * @param string $name * * @return HHPnet\Core\Domain\Songs\Song */ public function getBySongByName(AlbumId $album_id, $name) { $song = $this->collection->findOne(['album_id' => $album_id, 'name' => $name]); return $this->getSongInstance($song); }
<?php try { // included for debugging purposes - should be removed in any production code ini_set('display_errors', 1); date_default_timezone_set("UTC"); // include the mongodb library require 'vendor/autoload.php'; // connect to the database. replace "mongo-example.eur_usd" with where you imported the sample dataset //$manager = new MongoDB\Driver\Manager("mongodb://*****:*****@10.99.0.78:27017/mongo-example"); $collection = new MongoDB\Collection($manager, "mongo-example.eur_usd"); // set some constants that are used further in the code $limit = 1000; $timeField = 'date'; $valueField = 'rate'; // create the filter conditions. in real life application if you need to add any additional filters, // you should modify the $filter array, for example: // $filter['category'] = $_REQUEST["category"]; $filter = []; if (isset($_GET["from"]) && $_GET["from"]) { if (!isset($filter[$timeField])) { $filter[$timeField] = []; } $filter[$timeField]['$gte'] = new MongoDB\BSON\UTCDateTime($_GET["from"]); } if (isset($_GET["to"]) && $_GET["to"]) { if (!isset($filter[$timeField])) { $filter[$timeField] = []; } $filter[$timeField]['$lt'] = new MongoDB\BSON\UTCDateTime($_GET["to"]);
<?php try { // included for debugging purposes - should be removed in any production code ini_set('display_errors', 1); date_default_timezone_set("UTC"); // include the mongodb library require 'vendor/autoload.php'; // connect to the database. replace "mongo-example.continental" with where you imported the sample dataset $manager = new MongoDB\Driver\Manager("mongodb://*****:*****@10.99.0.78:27017/mongo-example"); $collection = new MongoDB\Collection($manager, "mongo-example.continental"); //filter - conditions to limit search results $filter = null; //limit - optional limit for aggregation results $limit = 10000; //put_id - whether to add ID to values or not. $put_id = true; //id - id of requested top section. Like name of continent - "Europe" in this example. $id = ""; $sort_field = "sum"; //group_field - field for aggregation grouping, by defult at first we want results grouped by "continent". $group_field = '$continent'; //extra_fields - additional fields for mongo aggregation to be returned $extra_fields = []; //ord -1 means descending, 1 - ascending. $ord = -1; //Case if section id is passed along request. This is where we read our //custom made ID and then understand if this is first level of drilldown or //second one. Based on the level of drilldown we set group_field and other //parameters as needed. if (isset($_GET["id"]) && $_GET["id"]) {
<?php require_once __DIR__ . "/bootstrap.php"; $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017"); $collection = new MongoDB\Collection($manager, "phplib_demo.write"); $hannes = ["name" => "Hannes", "nick" => "bjori", "citizen" => "Iceland"]; $hayley = ["name" => "Hayley", "nick" => "Ninja", "citizen" => "USA"]; $bobby = ["name" => "Robert Fischer", "nick" => "Bobby Fischer", "citizen" => "USA"]; $kasparov = ["name" => "Garry Kimovich Kasparov", "nick" => "Kasparov", "citizen" => "Russia"]; $spassky = ["name" => "Boris Vasilievich Spassky", "nick" => "Spassky", "citizen" => "France"]; try { $result = $collection->insertOne($hannes); printf("Inserted _id: %s\n\n", $result->getInsertedId()); $result = $collection->insertOne($hayley); printf("Inserted _id: %s\n\n", $result->getInsertedId()); $result = $collection->insertOne($bobby); printf("Inserted _id: %s\n\n", $result->getInsertedId()); $count = $collection->count(["nick" => "bjori"]); printf("Searching for nick => bjori, should have only one result: %d\n\n", $count); $result = $collection->updateOne(["citizen" => "USA"], ['$set' => ["citizen" => "Iceland"]]); printf("Updated: %s (out of expected 1)\n\n", $result->getModifiedCount()); $cursor = $collection->find(["citizen" => "Iceland"], ["comment" => "Excellent query"]); echo "Searching for citizen => Iceland, verify Hayley is now Icelandic\n"; foreach ($cursor as $document) { var_dump($document); } echo "\n"; } catch (Exception $e) { printf("Caught exception '%s', on line %d\n", $e->getMessage(), __LINE__); exit; }
<?php try { // included for debugging purposes - should be removed in any production code ini_set('display_errors', 1); date_default_timezone_set("UTC"); // include the mongodb library require 'vendor/autoload.php'; // connect to the database. replace "mongo-example.cities" with where you imported the sample dataset $manager = new MongoDB\Driver\Manager("mongodb://*****:*****@10.99.0.78:27017/mongo-example"); $collection = new MongoDB\Collection($manager, "mongo-example.cities"); //Example of coordinates: /* $coordinates = [ "north" => "56.97457345228613", "south" => "56.9511767654851", "west" => "24.115977287292477", "east" => "24.20009136199951" ]; */ //Read coordinates from $_GET variable: $coordinates = $_GET; $match = null; //creat $match variable for MongoDB //coordinates must be converted to (double) as in MongoDB records are stored asn double // and in PHP coordinates comes as string $match = ["lng" => ['$gte' => (double) $coordinates["west"], '$lte' => (double) $coordinates["east"]], "lat" => ['$gte' => (double) $coordinates["south"], '$lte' => (double) $coordinates["north"]]]; //execute query: $cursor = $collection->find($match, []); //just convert stdClass to array: $iterator = iterator_to_array($cursor);