0

I am new to MongoDB.

I am using Jensegger/Laravel-MongoDB Moloquent features to work on Mongo DB.

I am trying to create an index of a collection in this method:-

Schema::collection('events', function ($table) {
     $table->index(['location' => '2dsphere']);
});

However, I am getting error:-

Class Jenssegers\Mongodb\Schema' not found

I have added these two as well:-

use Jenssegers\Mongodb\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

I have a controller method which is given below:-

public function fetchMongoTest(Request $request){
    $error = FALSE;
    $respond = array();
    $detail = array();
    $err_message = array();
    $err_validation = array();
    $api_code       = 2001; 
    try 
    {
        if ($request->isMethod('post')) 
        {
            $latitude = (float)$request->latitude;
            $longitude = (float)$request->longitude;
            $status     = 1;
            $mongoData = array();
            $monTestObj = new Mongotest;

            Schema::collection('events', function ($table) {
                $table->index(['location' => '2dsphere']);
            });

            $monTestObj->location = ['type' => 'Point', 'coordinates' => [100.0, 0.0]];
            $monTestObj->save();



            $users = MongoTest::where('loc', 'near', [
                '$geometry' => [
                    'type' => 'Point',
                    'coordinates' => [
                        $longitude,
                        $latitude
                    ]
                ],
                '$maxDistance' => 10,
            ]);

            foreach($users as $u)
                {
                    print_r($u->name);
                }


        }
        else 
        {
            $status     = 0;
            $message    = Config::get('customConfig.api_messages.ENG.post_request_mandatory');
            $err_message[] = $message;
        }
    }
    catch(Exception $e) 
    {
        $status = 0; 
        echo $e->getMessage(); die;
        $message=Config::get('customConfig.api_messages.ENG.exception_error');
    }
    $response['status']         = $status;
    $response['message']        = $message;
    $response['details']        = $detail;
    $response['error']          = $err_message;
    $response['error_validation_key'] = $err_validation;
    $response['api_version']    = $this->api_version;
    $response['api_code']       = $api_code;

    $respond['fetch-activity-list-prime'] = $response;
    $jsonResult = json_encode($respond);    
    header('Content-Type: application/json; charset=utf-8');    
    echo $jsonResult ;      
    exit();
}

How can I check if a collection exists and if not, create a new collection?

EDIT:

This is my MongoTest model:-

<?php
namespace App\Http\Model;
//use Illuminate\Database\Eloquent\Model;
use Moloquent;
class MongoTest extends Moloquent
{
    protected $connection = 'mongodb';
    protected $collection = 'test';
    //protected $collection = 'rh_country_help_text';
}
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Saswat
  • 12,320
  • 16
  • 77
  • 156
  • You're not trying to create a collection, you're trying to create an index. And you're doing it on the wrong field as from your previous question. DDL things really don't belong in an application anyway. These should be set up independently, and especially so within production environments where there are real considerations of avoiding downtime and optimization when creating indexes. – Neil Lunn May 18 '18 at 07:14
  • Could you please suggest step by step to do what is required? I am working on the Moloquent feature and it says, it can be done using the library. – Saswat May 18 '18 at 07:18
  • I'd probably start by acknowledging that you already asked a question about an index and were shown what to do and yet still have not accepted the answer. That would be **step 1** if you expect to ask further questions and receive help for them – Neil Lunn May 18 '18 at 07:20
  • I want that step to be written in a Laravel model. The syntaxt propbaly isn't supported in Laravel. – Saswat May 18 '18 at 07:22
  • Where have you defined `MongoTest`? Show that as none of the other code here is really relevant. We just need to see how the collection name is defined. – Neil Lunn May 18 '18 at 07:30

1 Answers1

7

You seems to have picked up a partial answer from somewhere. The Schema should be picked up from a "Larvel Migration", which is one recommended way of actually defining indexes in your application.

The process would be to set up like:

Create the Migration

php artisan make:migration create_location_index

Then alter the structure to add the up and down for create and drop of the index:

<?php

    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;

    class CreateLocationIndex extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::connection('mongodb')->table('test', function (Blueprint $collection) {
                $collection->index([ "loc" => "2dsphere" ]);
            });
        }

        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::connection('mongodb')->table('test', function (Blueprint $collection) {
                $collection->dropIndex(['loc_2dsphere']);
            });
        }
    }

Then you can run the migration as detailed within the documentation

If you decide to run the code outside of a migrations process then alternate handles for getting the MongoDB\Collection object can be like:

DB::collection('test')->raw(function($collection) {
  return $collection->createIndex([ 'loc' => '2dsphere' ])
}

Whatever you do though this code does not belong in the controller. The code to create an index need only be run once. Typically "once only" on your database deployment, but it does not really hurt to issue the command on every application start up, however it certainly hurts with every request. So just don't put it there.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317