Showing posts with label DB. Show all posts
Showing posts with label DB. Show all posts

MongoDB Crud Operation and Mongo DB Crud

MongoDB Crud Operation

MongoDB Crud Operation Basics


Create studentInfo Database in MongoDB server. Use the below code for creating the DB.


Above use studentInfo command will create the DB in MongoDB Server. If studentInfo DB will exist then it will switch to that instead of creating it. To view the created database in the list you must have to create at least one collection in that.

MongoDB provide db.createCollection() method to create collection in database. Command to create studnet collection in studentInfo Database is below 


Press Enter collection will be created in studentInfo Database with the name of student. To view all the collection in the studentInfo Database use below command. Below command will list all the collection present in the studentInfo Database. 

Insert or Create Document in MongoDb Collection


To insert document in the collection in MongoDB Database. We use below two command to insert the document.

  • db.collectionName.insertOne()
  • db.collectionName.insertMany()

Using above two method we will insert the document in the student Collection of studentInfo Database. 

This below command will insert one document in student Collection.

db.student.insertOne(
   { 
     "id":1,
     "name":"Manoj Kumar",
     "dob":"2003-04-07",
     "marks":54,
     "created_at":"2017-11-13 23:33:42"
   }
)

To Insert many document at a time we have to use db.collectionName.insertMany() method . Below is the code for inserting many document at a time. We can pass all the document as a array.

db.student.insertMany([
   { 
     "id":2,
     "name":"MOHAMMED  H",
     "dob":"2002-06-14",
     "marks":67,
     "created_at":"2016-11-13 23:33:42"
   },
   { 
     "id":3,
     "name":"ANBUSELVAM S",
     "dob":"2004-06-18",
     "marks":87,
     "created_at":"2019-11-13 23:33:42"
   }
 ])



Fetch Or Retrieve Document from Collection


To retrieve or fetch the document from the MongoDB collection we use db.collectionName.find() method.
  • db.student.find() method will fetch all the document from the specified MongoDB collection. This above method will fetch all the document in single line which will not be in readable format.
  • db.student.find().pretty() method will fetch and arrange the collection document in some proper readable format. pretty() method will give you the output is below for reference. 

MongoDB Operators and Query Example


We can apply various filter on mongoDB collection document based on certain condition. We can use various operator also for document filter. Below is the query list and condition to demonstrate the filtration.

$eq (=)
$eq will match the value with specified value.
$gt (>)
$gt will check that the value is greater than specified value.
$gte (>=)
$gte will check that the value is greater than equal to specified Value.
$in (IN)
$in will check that specified value is there in range or not.
$nin (NOTIN)
$nin will check that specified value not lies in the range.
$lt (<)
$lt will check that the value is less than the specified value
$lte (=<)
$lte will check that the value is less than the specified value
$ne (!=)
$ne will check whether the value not equal to specified value


$and
Logical AND join multiple query clause and compare multiple clause and return value as True or False.
$not
Logical NOT Check the query expression and return the result.
$nor
Logical NOR join multiple query clause and compare multiple clause
$or
Logical OR  join multiple query clause and compare multiple clause and return value as True or False

Some Query Example using above operator is below for reference with output.

  •  db.student.find({marks:{$eq:43}}).pretty()     O/P is below                                                                                             
    mongoDB Comparision Operator Example

  • db.student.find({marks :{$gte:70}}).pretty()  O/P is below                                                                                 
    $gte operator in MongoDB

  • db.student.find({marks :{$in:[54, 87]}}).pretty()  O/P is below                                                                         

Query Using AND Logical Operator in MongoDB


  • db.student.find({$and :[{name : "JAGAN J"},{marks :98}]}).pretty()                                               {
            "_id" : ObjectId("5ebeaafd50845b5c0ea8bf58"),
            "id" : 5,
            "name" : "JAGAN J",
            "dob" : "2003-04-10",
            "marks" : 98,
            "created_at" : "2012-11-13 23:33:42"
        }


Query Using OR Logical Operator in MongoDB

  • db.student.find({$or :[{name:"JAGAN J"},{marks :{$gt:70}}]}).pretty()                                     {
            "_id" : ObjectId("5ebeaafd50845b5c0ea8bf56"),
            "id" : 3,
            "name" : "ANBUSELVAM S",
            "dob" : "2004-06-18",
            "marks" : 87,
            "created_at" : "2019-11-13 23:33:42"
    }
    {
            "_id" : ObjectId("5ebeaafd50845b5c0ea8bf58"),
            "id" : 5,
            "name" : "JAGAN J",
            "dob" : "2003-04-10",
            "marks" : 98,
            "created_at" : "2012-11-13 23:33:42"
    }

Query Using AND Operator as well as OR in MongoDB


  • db.student.find({marks :{$lt : 99}, $or :[{marks :{$in:[43,98]}},{name : "JAGAN J"}]}).pretty()                                                                                                                                  {
            "_id" : ObjectId("5ebeaafd50845b5c0ea8bf57"),
            "id" : 4,
            "name" : "MARTINPRIYADOSS J",
            "dob" : "2004-03-08",
            "marks" : 43,
            "created_at" : "2012-11-13 23:33:42"
    }
    {
            "_id" : ObjectId("5ebeaafd50845b5c0ea8bf58"),
            "id" : 5,
            "name" : "JAGAN J",
            "dob" : "2003-04-10",
            "marks" : 98,
            "created_at" : "2012-11-13 23:33:42"
    }

MongoDB Update Query

Update query in MongoDB is done using below method.
  • db.collection.updateOne() 
  • db.collection.updateMany() 
  • db.collection.replaceOne()

Delete Operation In MongoDB

Delete Query in MongoDB is done using below method.
  • db.collection.deleteOne() 
  • db.collection.deleteMany() 

Laravel Model and Database Migration From Scratch

Laravel Database Migration


Laravel Database Migration is way through which we build and maintain the Database Schema. Migration is Version Control of Your DB, which will allow Developer team easily to modify and share the DB Schema.

Laravel DB Migration provide the facility for those who is not able and poor in maintaining, updating Database.

Migration In Laravel contain by default Two method up() method is called when a DB is modified or changed. Whereas, the DB Migration down() method is called when DB is reverted back.


create migration in laravel

Step 1: Create Laravel Project with Name anyQuestion using Composer. Command to create project in laravel is below.

composer create-project --prefer-dist laravel/laravel anyQuestion "6.*"

anyQuestion is our Laravel Project name. Below is the Screen what will appear while creating the project using Command prompt.


Step 2: Create Database named with anyQuestion_db in Xampp or whatever server tool you use. Open .env file in your laravel project and configure your Database with password and all.

Step 3:  Use Php Artisan Command to create model and controller in your project.

php artisan make:controller controllerName

This above artisan command will create normal controller without default function.

php artisan make:controller controllerName --resource

This above Artisan Command will create controller with default function in it. All the default Function list is below.

  • public function index(){ }
  • public function create(){ }
  • public function store(Request $request){ }
  • public function show($id) { }
  • public function edit($id) { }
  • public function update(Request $request, $id){ }
  • public function destroy($id) { }

If we are creating the Controller with --resource then by default all the above function will be created and creating route for all the above function will be time consuming process. So view the route list first using below artisan command. below command will give you all the route list.

php artisan route:list

How to define single route which will point all the above function based on the requirement.

 Route::resource('route-name','controller-Name');

Again hit the php artisan route:list  And you can view all the route list for default controller function.

Now create Model using artisan command, below is the command

php artisan make:model model-Name

Above command will create the simple model with sample model name what is provided with the command.

Laravel Run Migrations


Database migration concept start with model here. Database migration in Laravel provide the facility to create, manage and modify the database. Create Model with migration using Artisan Command. Below is the command to create Model with migration.

  php artisan make:model model-Name  -m (-m is for migration )

Now check your Migration folder inside Database Folder in the anyQuestion project root.

In the migration folder the migration file will be created and if you open that you will get default up() function and down() function.

   public function up()
     {
        Schema::create('post_masters', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
     }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('post_masters');
    }

If you check the post_master migration file, In up() function we are creating post_masters table.  By default there is 'id' column and the timestamp which will give us the 'created_at', 'updated_at' column.

Once you have created the model with migration you don't have to touch the Database to create table. You can directly migrate the file using below command which will create the table in the database. To add column or remove column you just make change in the migration file. and using artisan command it will reflect in the Database. Command to migrate the files.

Before Migration go to Provide Folder and Open the AppServiceProvider.php file and add this line of code. Open AppServiceProvider.php file

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        // 
}

Once change is made run the migration Command which is below for your reference.

php artisan migrate

The Artisan command will run it will create the table automatically in the Database..

How to insert the record in Database using Artisan Command


Insert Data Using Tinker

Our Feature Post

There is a tree between houses of A and B If the tree leans on As House

    There is a tree between houses of A and B. If the tree There is a tree between houses of A and B. If the tree leans on A’s House, the t...

Our Popular Post