Friday 22 November 2019

How to setup different configs in server (development, production)?

How to implement different configs for development, production?

Question: How to implement different configs for development, production etc?
  1. Added following line in .htacess (Location: /public/.htaccess)
    SetEnv APPLICATION_ENV development
    This is for development.
  2. Open application.config.php in /config/application.config.php
  3. Get the current environment.
    $applicationEnv = getenv('APPLICATION_ENV');

    Dynamic the file like below:
            'config_glob_paths' => array(         
                "config/autoload/{,*.}{$applicationEnv}.php"
            )
  4. Create the config files like below in /config/autoload
    development.php
    production.php
    
  5. Below are the sample of config file.
    return array(
        'db' => array(
            'driver' => 'Pdo',
            'dsn' => 'mysql:dbname=DBNAME;host=HOST',
            'username' => 'DB_USERNAME',
            'password' => 'DB_PASSWORD'
        )
    );
    Please update the database credentials.

Saturday 16 November 2019

How to Send Tweets automatically with PHP?

How to Send Tweets automatically with PHP?


Basic Requirements
  1. An Twitter account.
  2. An Twitter app. If don't have please create @ https://apps.twitter.com
  3. Twitter Auth REST API, If don't have please download from https://github.com/abraham/twitteroauth
  4. An Server, You can also test in local wampserver or xampserver


How to Send Tweets automatically with PHP, Follow following Steps:
  1. Include twitter files.
    require_once($_SERVER['DOCUMENT_ROOT'].'/twitteroauth/twitteroauth.php');
    require_once($_SERVER['DOCUMENT_ROOT'].'/twitteroauth/config.php');
  2. Collect all constants values from your twitter app (i.e apps.twitter.com)

  3. Add constants in TwitterOAuth constructor.
    define('CONSUMER_KEY', 'YOUR_KEY');
    define('CONSUMER_SECRET', 'YOUR_SECRET_KEY');
    define('ACCESS_TOKEN', 'YOUR_TOKEN');
    define('ACCESS_TOKEN_SECRET', 'YOUR_TOKEN_SECRET');
    
  4. $twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
  5. Now post the message.
    $message='This is test tweet.';
    $twitter->post('statuses/update', array('status' => $message));
  6. Refresh the twitter.com, you will see your message at top of page.

Saturday 9 November 2019

Paypal Mass Payment - Pay with email Address

Paypal Mass Payment - Pay with email Address

Mass Pay. Merchants can use the Mass Pay API to send money instantly to multiple recipients at once.


Question: Can I pay someone with their email address (Manual Transaction)?
Yes, you can pay.


Question: When money will deduct from sender account(Manual Transaction)?
As soon as you pay, money will be deducted from the sender account.


Question: When money will be credited to the receiver account(Manual Transaction)?
When you pay with email address and that email is already register with paypal.
Money will be credited immediately.

If email address is not registered, then receiver will get an email from paypal and he need to follow the steps in email to received.


Question: When money will deduct from sender account(Manual Transaction)?
As soon as you pay, money will be deducted from the sender account.


Question: What are transaction charges (Manual Transaction)?
If you are paying to your friend/family member and they are within same country - Its Free.
If you are paying for commerical purpose, No transaction charges for Sender/Buyer and (2.3% +.30 USD) will be deducted from seller/reciever.


Question: Can I can Cancel the payment after sending?
You can cancel only if he has not accept the payment.
but receiver can refund money to you.


Question: Is there any API available to pay with email address?

You can use MassPay API OR Adaptive Payments API. Question: What is Mass Paypal?
In this case, One Merchant can send the money to his partner's paypal email address (Paypal email address), mean each merchant must have paypal account. https://developer.paypal.com/docs/classic/mass-pay/integration-guide/MassPayOverview/


Question: What are keys of Mass Paypal through API?
  1. When we send payment with email address PayPal takes the payment amounts from your account and attempts to put them into the recipients' PayPal account.
  2. If the recipients do not have PayPal accounts, PayPal notifies them that a payment is available and they must create a PayPal account to receive the payment.
  3. Payments processing can take from a couple of minutes to several hours.
  4. PayPal will temporarily hold the total monetary value of the mass payment, plus associated fees, until processing is completed.
  5. If a payment is sent to a recipient who does not have a PayPal account, and it remains unclaimed for 30 days from the payment date, the money is returned to your PayPal account.
  6. Mass Payments need to enable for PayPal.
  7. You can only cancel payments that have an unclaimed payment.



Question: What is Mass Paypal Request parameter?
Array
(
    [METHOD] => MassPay
    [USER] => testname_api1.no-spam.ws
    [PWD] => 55555526677
    [SIGNATURE] => Alsdfdsfafdsfs.zYsROoDYkL2AigOq
    [VERSION] => 95
    [RECEIVERTYPE] => EmailAddress
    [CURRENCYCODE] => USD
    [L_EMAIL0] => testnamel@no-spam.ws
    [L_AMT0] => 10.00
    [L_EMAIL1] => testname2@no-spam.ws
    [L_AMT1] => 10.00
)



Git interview questions and answers - Problem and Solutions


Git interview questions and answers - Problem and Solutions

Question: How to delete a Git branch both locally and remotely?
To remove a local branch from your local system.
git branch -d the_local_branch

To remove a remote branch from the server.
git push origin :the_remote_branch



Question: How do you undo the last commit?
git revert commit-id



Question: How to Edit an incorrect commit message in Git?
git commit --amend -m "This is your new git message"



Question: What are the differences between 'git pull' and 'git fetch'?
Git pull automatically merges the commits without letting you review them first.
Git fetch stores them in your local repository but it not merge them with your current branch.
git fetch similar to guit pull but it does not merge the changes.


Question: How do you rename the local branch?
git branch -m oldBranchName newBranchName



Question: How do I remove local files (Not in Repo) from my current Git branch?
git clean -f -n


Question: How to Checkout remote Git branch?
git checkout test



Question: How do I remove a Git submodule?
git rm the_submodule
rm -rf .git/modules/the_submodule



Question: How do you create a remote Git branch?
git checkout -b your_branch_name
git push -u origin your_branch_name



Question: How to Change the URL for a remote Git repository?
git remote set-url origin git://this.is.new.url



Question: How to Change the author of a commit in Git?
git filter-branch -f --env-filter "GIT_AUTHOR_NAME='NewAuthorName'; GIT_AUTHOR_EMAIL='authoremail@gmail.com'; GIT_COMMITTER_NAME='CommiterName'; GIT_COMMITTER_EMAIL='committergmail@gmail.com';" HEAD



Question: What is .gitignore?
.gitignore tells git which files/folder should be ignore.
Create a file with name of .gitignore in root.
temporay files, system files, hidden files or local downloaded modules we can add in .gitignore file, so that git will not added this.


Question: How do I delete a Git branch locally?
git branch -d {the_local_branch}


Question: How do I delete a Git branch remotely?
git push origin --delete {the_remote_branch}
(use -D instead to force deleting the branch without checking merged status)


Question: What is the difference between git pull and git fetch?
git pull does a git fetch followed by a git merge.



Question: How do I undo git add before commit?
git reset file.php



Question: How do I rename a local Git branch?
git branch -m oldname newname




Question: How do I discard unstaged changes in Git?
git stash save --keep-index --include-untracked

You don't need to include --include-untracked if you don't want to be thorough about it.
After that, you can drop that stash with a git stash drop command if you like.


Sunday 3 November 2019

Node.js questions and answers for 1 year experience

Node.JS questions and answers for 1 year experience

Question: How to update NPM?
npm install -g npm



Question: How to write in file through NodeJs?
For this, you need to use filesystem API.
var fs = require('fs'); //Create Object
var fileName='/tmp/myfile.txt';
var fileContent='Hello this is text message';
fs.writeFile(fileName, fileContent, function(err) {
    if(err) {
        return console.log('error:'+err);
    }
    console.log("Content saved in File successfully");
}); 



Question: How to check File Exist OR Not?
For this, you need to use filesystem API.
var fs = require('fs');
var fileName='/tmp/myfile.txt';
if (fs.existsSync(fileName)) {
    console.log('File Exist');
}else{
 console.log('File Does not Exist');
}



Question: How to remove a file?
For this, you need to use filesystem API.
var fs = require('fs');
var fileName='/tmp/myfile.txt';
fs.unlinkSync(fileName);



Question: How to read process EVN?
console.log(process.env)
Output
{ 
  ENV_NODE_CONSOLE: 'production',
  DYNO: 'web.1',
  PATH: '/app/vendor/node/bin:/app/bin:/app/node_modules/.bin:bin:node_modules/.bin:/usr/local/bin:/usr/bin:/bin',
  PWD: '/app',
  MONGOLAB_URI: 'mongodb://heroku_app14996339_A:PQrhCoawHlCQcpOQNRkBeEbXLXnhYNSz@ds043987.mongolab.com:43987/heroku_app14996339',
  PS1: '[033[01;34m]',
  NODE_ENV: 'production',
  SHLVL: '1',
  HOME: '/app',
  NO_CLUSTER: 'true',
  PORT: '24118',
  _: '/app/vendor/node/bin/node'
 }



Question: How to retrieve POST query parameters in Express?
app.post('/test-page', function(req, res) {
    console.log(req.body);//here is post data
});



Question: How to encode a sting using base64_encode?
console.log(new Buffer("1").toString('base64')); //MQ==



Question: How to decode a sting using base64_decode?
console.log(new Buffer("MQ==", 'base64').toString('ascii'));//1



Question: How can I pretty-print JSON using node.js?
var testVar ='{ a:1, b:2, c:3 }, null, 4';
JSON.stringify(testVar);



Question: How to exit in Node.js?
process.exit()
.


Question: How to exit from unix terminal in Node.js?
ctr+c twice




Saturday 2 November 2019

PHP interview questions and answers for 3 year experience

PHP interview questions and answers for 3 year experience

Question: Are PHP functions case sensitive?
Inbuilt function are not sensitive.
User defined functions are senstivie.

Case sensitive (both user defined and PHP defined)
  1. variables
  2. constants
  3. array keys
  4. class properties
  5. class constants

Case insensitive (both user defined and PHP defined)
  1. functions
  2. class constructors
  3. class methods
  4. keywords and constructs (if, else, null, foreach, echo etc.)






Question: How to return call by reference value from function?
Just use &(ampersand) before the function name.
For Example.
function &showData($data){
   $data.=' New String';    
   return $data;
}



Question: How to check a form is submited OR Not?
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    //form is submitted
}



Question: How to remove all leading zeros from string?
echo ltrim('00000012', '0'); //12



Question: How to find HTTP Method?
$_SERVER['REQUEST_METHOD']
It will return GET, HEAD, POST, PUT etc


Question: How to Serializing PHP object to JSON?
$userModel = new UserModel();
echo json_encode($userModel);//serialize data



Question: How to get current URL of web page?
echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];



Question: How to add N number of days in an data?
echo date('Y-m-d', strtotime("+30 days"));



Question: How to get Yesterday date?
echo date("F j, Y", time() - 60 * 60 * 24); //November 1, 2016


Question: What's the maximum size for an int in PHP? The size of an integer is platform-dependent
Maximum value of about two billion for 32 bit system.


Question: How to remove all specific characters at the end of a string?
$string = 'Hello. * cool';
echo $string = str_replace(array('*', '.',' '), '', $string); //Remove * . and space [you can add more as you want]




Monday 21 October 2019

Symfony2 Interview Questions and Answers for Beginners

Symfony2 Interview Questions and Answers for Beginners

Question: What is Symfony?
Symfony is a PHP web application framework for MVC applications.


Question: Is Symfony Open Source?
Yes, It is Open Source.


Question: What is current Stable version of Symfony?
Version: 5.0.4, Dated: 31 Jan 2020


Question: What is offical website of Symfony?
symfony.com


Question: What is minimum PHP Version requirement for Symfony?
PHP 7.2.5


Question: What are benefits of Symfony?
  1. Fast development
  2. MVC Pattern
  3. Unlimited flexibility
  4. Expandable
  5. Stable and sustainable
  6. Ease of use.



Question: How to concatenate strings in twig?
{{ 'http://' ~ app.request.host }}



Question: How to get current route in Symfony 2?
$request = $this->container->get('request');
$currentRouteName = $request->get('_route');



Question: How to render a DateTime object in a Twig template?
{{ game.gameDate|date('Y-m-d') }}



Question: How to var_dump variables in twig templates?
{{ dump(user) }}



Question: How to get the request parameters in symfony2?
$name=$request->query->get('name');



Question: How to get list of all installed packages in composer?
composer global show


Sunday 13 October 2019

How to create http server in NodeJS?

How to create http server in NodeJS?

Question: How to create a New server in nodejs?

var http = require("http");
http.createServer(function(request, response) {    
response.writeHead(200, {'Content-Type': 'text/html'});    
response.write("<html>");
response.write("<head>");
response.write("<title>Hello World Page</title>");
response.write("</head>");
response.write("<body>");
response.write("Hello World!");
response.write("</body>");
response.write("</html>");
    response.end();
}).listen(8081);



Question: How to Execute above response in browser?
http://127.0.0.1:8081/
You should be already installed WampServer/Xampp Server.


Question: How to install httpdispatcher?
npm install httpdispatcher



Question: Give an example of http GET Request?

dispatcher.onGet("/contactus", function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('<h3>
Contact US Page</h3>
');
});



Question: Give an example of http POST Request?

dispatcher.onPOST("/contactus", function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('<h3>
Received POST Data</h3>
');
});



Question: Give an full example of httpdispatcher which have multiple pages?

var dispatcher = require('httpdispatcher'); 
function handleRequest(request, response) {
    try {
        //log the request on console
        console.log(request.url);
        //Disptach
        dispatcher.dispatch(request, response);
    } catch (err) {
        console.log(err);
    }
}
dispatcher.setStatic('resources');

//A sample GET request    
dispatcher.onGet("/contactus", function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('<h3>
Contact US Page</h3>
');
});

dispatcher.onGet("/aboutus", function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('<h3>
About US Page</h3>
');
});


var http = require('http');
var server = http.createServer(handleRequest);
//Lets start our server
server.listen(8081, function() {
    //Callback triggered when server is successfully listening. Hurray!
    console.log("Server listening on: http://localhost:%s", 8081);
});




Saturday 12 October 2019

How to install and Connect to MySQL in NodeJS?

How to install and Connect to MySQL in NodeJS?

Hope you have already installed nodeJS, If not Please install first.
https://nodejs.org/en/download/

Question: How to install new package in nodejs?
npm install packagename



Question: How to install MySQL?
npm install mysql



Question: How to update MySQL?
npm update mysql



Question: How to include MySQL?
var mysql = require("mysql");



Question: How to connect to MySQL in nodeJS?
var mysql = require("mysql");
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "mydb"
});
con.connect(function(err) {
    if (err) {
        console.log('Error connecting to database');
        return;
    }
    console.log('Connection established Successfully');
});



Question: How to connect to MySQL in single string in nodeJS?
var mysql = require("mysql");
var con = mysql.createConnection('mysql://arun:arun@localhost/database'); 
con.connect(function(err) {
    if (err) {
        console.log('Error connecting to database');
        return;
    }
    console.log('Connection established Successfully');
});



Question: How to get records from MySQL database in node.js?
var mysql = require("mysql");
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "enterprisedev2"
});

con.query('SELECT * FROM admin_members where id<=10 ', function(err, rows) {
    for (var i = 0; i < rows.length; i++) {
        console.log(rows[i]);
    }
});


Question: How to insert record in database?
var mysql = require("mysql");
var con = mysql.createConnection('mysql://arun:arun@localhost/mydb');
var post = {
    'userID': "1",
    'userName': 'username',    
    'device': 'web',
    'stream_time': "0",
    'user_display_name': "arun kumar gupta",
    'user_photo': "hello"
};
con.query('INSERT INTO messages set ?', post, function(err, result) {
    if (err) {
        console.log(err.message);
    } else {
        console.log('record added in db');
    }
});



Question: How to print the query while inserting record?
var mysql = require("mysql");
var con = mysql.createConnection('mysql://arun:arun@localhost/mydb');
var post = {
    'userID': "1",
    'userName': 'username',    
    'device': 'web',
    'stream_time': "0",
    'user_display_name': "arun kumar gupta",
    'user_photo': "hello"
};
var mysqlProfiler = con.query('INSERT INTO messages set ?', post, function(err, result) {});
console.log(mysqlProfiler.sql);



Question: Given another way to insert data in MySQL Database?
var mysql = require("mysql");
var con = mysql.createConnection('mysql://arun:arun@localhost/enterprisedev2');

/* data insert in db */
var postData = {
    userID: "1",
    userName: "arunkg",
    userRole: "1",
    text: 'kkkkkkkkkkkkkkkk',
    status: "1",
    vid: '21'
};

var mysqlProfiler = con.query('INSERT INTO `messages` (`userID`, `userName`, `userRole`,`text`,`status`,`vid`) VALUES (' + [postData.userID, mysql.escape(postData.userName), postData.userRole, mysql.escape(postData.text), postData.status, postData.vid] + ')', function(err, result) {
    if (err) {
        //console.log(err.message);
    } else {
        console.log('record added in db');
    }
});



Thursday 10 October 2019

How to speed up your application with MongoDb?

How to speed up MongoDb?

1) Make Sure you application have Sufficient RAM
If your application don't have enough RAM, then please increase it.


2) Analyze Your Queries
Analyse the queries with explain like below:
db.user.find('{"likes": {$gt:10}"likes"}').explain("executionStats");
You can check the problem with the queries and fix the issue.
Also please fetch only those records which are using. Don't fetch un-necessary field and records from database.


3) Limit the Records
If you are using 10 records but getting 100 records. Means you are getting 99 record extra that is wrong. So please limit the record with limit command.
db.user.find('{"likes": {$gt:10}"likes"}').limit(10);



4) Add Appropriate Indexes
You can use the index wherever are required (most used in search query). You can add indexes on Single/Multiple field. In this way you can speed the application by speedup the queries.
db.user.createIndex({ country: 1 });



5) Sorting
Un-necessary sorting can also have problem, So sort the records wherever required. Avoid un-necessary sorting. Example of Sorting (-1 no sorting, 1 ascending , 0 descending )
Sort by Country and then City.
db.user.find().sort({ country: 1, city: 1 });

Sort by Country only (Even we have added city in our indexes).
db.user.find().sort({ country: 1, city: -1 });

Sort by city only (Even we have added country in our indexes).
db.user.find().sort({ country: -1, city: 1 });



6) Check Your MongoDB Log
As we know, logging the queries take some time to logged. It make take about 100Mili seconds for each log query.
So, You should log the queries carefully because un-necessary loging data may slow the system.
db.setLogLevel(0);
0 is the MongoDB's default log verbosity level, to include Informational messages.
1 to 5 increases the verbosity level to include Debug messages.


7) Understand the Query Profiling
You can get Profiling Level (current).
db.getProfilingLevel()

You can set Profiling Level.
db.setProfilingLevel(1)

Following the 3 Profiling Level.
  1. -1 for inherit the profiling from parent.
  2. 0 for no profiling.
  3. 1 for slow operations.
  4. 2 for all operations.

8) Multiple Database Connection
If you are running heavy site and few queries are taking taking more time due to which queries are completing in asynchronous.
Means query start time are q1, q2, q3 but completing time are q2,q1,q3.
To fix this problem.
For this, you can create multiple Database connection and handle like below:
  1. One to handle the majority of fast queries.
  2. One to handle slower document inserts and updates.
  3. One to handle complex report generation.



9) Set Maximum Execution time

MongoDB commands run as long as they need. A slowly-executing query can hold up others, and your web application may time out.
You can set the max execution time like below:
db.user.find('{"likes": {$gt:10}"likes"}').maxTimeMS(100);



10) Rebuild Your Indexes

You need re-index, if your collection fall in following:
  1. Collection size has increased significantly.
  2. Indexes are consuming a disproportionate amount of disk space.



Saturday 5 October 2019

FuelPHP Interview Questions and Answers for Beginners

FuelPHP Interview Questions and Answers for Beginners

Question: What is FuelPHP?
FuelPHP is PHP Framework written in PHP, based on the HMVC pattern.


Question: Is FuelPHP Open Source?
Yes, It is Open Source.


Question: What is minimum PHP Version required for FulePHP?
PHP 5.4+


Question: Is FulePHP support Multilingual?
Yes, It support Multilingual.


Question: What is offical website of FulePHP?
fuelphp.com


Question: What are Key Features of FuelPHP?
  1. URL routing system
  2. RESTful implementation
  3. HMVC implementation
  4. Form Data validation
  5. ORM (Object Relational Mapper)
  6. Vulnerability protections like XSS, CSRF, SQL Protection and encode output.
  7. Caching System



Question: What is full form of HMVC?
Hierarchical-Model-View-Controller


Question: What is HMVC?
HMVC is an evolution of the MVC pattern.


Question: What are benefits of HMVC?
  1. Modularization
  2. Organization
  3. Reusability
  4. Extendibility



Question: How to get Query in FulePHP?
$userQueryToExecute = Model_Article::query()
        ->select('users')        
        ->where('blocked', '=', 1);

echo $userQueryToExecute->get_query();



Question: How to check that Redis server is running?
try
{
    $redis = \Redis::instance();    
}
catch(\RedisException $e)
{
    //here error will come
}



Question: How to use join with condition?
$queryObj = \Services\Model_Org::query()
->related('org')
->related('profile_image')->related( array(  'comments' => array(   'where' => array(    array('visible' , '=' , '0')   )
  ) ))
->where('rating','!=', 'null')
->order_by('rating','desc')
->get();


Thursday 3 October 2019

What is Super Key, Candidate keys and Alternate Key?

What is Super Key, Candidate keys and Alternate Key?

Super Key
A Super key is any combination of fields within a table that uniquely identifies each record within that table.

Example:
managers (table)
ManagerID (unique)
Name
Title
DepartmentID

ManagerID+Name=Super Key
ManagerID+Title=Super Key


Candidate keys
Candidate keys are those keys which is candidate for primary key of a table. Candidate keys are such keys which full fill all the requirements of primary key which is not null and have unique records.

Example:
Suppose we have a table named Employee which has two columns EmpID and EmpMail, both are not null and have unique value.
Both Field are Candidate keys.



Alternate Key
If any table have more than one candidate key, then after choosing primary key from those candidate key, rest of candidate keys are known as an alternate key of that table.

Example:
Suppose we have a table named Employee which has two columns EmpID and EmpMail, both are not null and have unique value.
So both columns are treated as candidate key.
IF we make EmpID as a primary key, then EmpMail is known as alternate key.



Referential integrity
Referential integrity is a database concept that ensures that relationships between two table remain consistent.

Suppose one table has a foreign key to another table. Referential integrity makes ensure the both have valid record.

Example:
products (table)
    id (primary key)
    name 
    price
    sale_price
    size

reviews (another table)
    id (primary key),    
    product_id (foreign key)
    review by
    title
    start_rating

One Product can have one Or multiple reviews.
Referential integrity make sure following:
  1. You can't delete record from product table, till review exist in reviews table for same product Id.
  2. You can't add record in reviews table, till you have not added record in product table for same product Id.
  3. If you delete the record from product table, reviews will be deleted automatically using cascade for the same product Id.



Friday 27 September 2019

MongoDB Questions and Answers for beginners

MongoDB Questions and Answers for beginners

Question: What kind of NoSQL database used in MongoDB?
MongoDB is a document oriented database. It store data in form of BSON structure.



Question: What is a Namespace in MongoDB?
Namespace is concatenation of the database name and collection name.



Question: Does MongoDB support foreign key constraints?
No.



Question: Does MongoDB support ACID transaction?
No.



Question: Does MongoDB support Indexes?
Yes.



Question: Does MongoDB support primary key & foreign key relationships in MongoDB?
No, By Default it does not support. But we can achieve this by using embedding one document inside another.



Question: How is MongoDB better than other SQL databases?
Namespace is concatenation of the database name and collection name.
  1. Highly flexible
  2. Scalable Document
  3. Fast
  4. Replication



Question: When we removed an document. Does it removed permanently?.
Yes, When we rmoved and document it delete from disk.


Question: When we removed an document. Does it removed permanently?.
Yes, When we rmoved and document it delete from disk.


Question: What happens if an index does not fit into RAM?.
In that case MongoDB reads data from disk which is relatively very much slower.


Question: What is a covered query in MongoDB?.
Covered query is the one in which, A) fields used in the query are part of an index
AND
B) the fields returned in the results are in the same index.


Question: What is Aggregation in MongoDB??.
Aggregation is process of data-records and return computed results.


Question: What is Sharding in MongoDB??.
Sharding is a method for storing data across multiple machines (2 OR more machines).


Question: What is Replication in MongoDB?.
Replication is a process of synchronizing data across multiple servers.


Question: What are Primary and Secondary Replica sets?
Primary and master nodes are the nodes that can accept writes.
Secondary and slave nodes are read-only nodes that replicate from the primary.


Question: Why are MongoDB data files large in size?
MongoDB preallocates data files to reserve space and avoid file system fragmentation when you setup the server.


Question: What is a Storage Engine in MongoDB?
A storage engine is responsible for managing data like how data is stored on disk.


Question: What are two storage engines used by MongoDB?
1) MMAPv1
2) WiredTiger


Question: Why MongoDB is not preferred over a 32-bit system??
In 32-bit build system the total storage size for the server including data and indexes is 2GB.


Question: What is the role of a profiler in MongoDB??
The Profiler collects fine grained data about MongoDB write operations, cursors, database commands.


Question: How does MongoDB provide concurrency?
MongoDB uses reader-writer locks for the concurrency.


Question: What is hotfix for windows?
A hotfix is single/cumulative package to fix an issue.


Question: How to changes in storage path of MongoDB?
mongod --dbpath "d:\mongodb\data"



Question: How to get mongoDB Version ?
mongod --version



Wednesday 25 September 2019

MongoDB indexing and Embed document

MongoDB indexing and Embed document

Question: How to create indexing on single column?
db.users.ensureIndex({"title":1})
1- Indexing in Ascending Order.


Question: How to create indexing on multiple column?
db.users.ensureIndex({"title":1,"description":-1})
1- Indexing in Ascending Order.
-1- Indexing in Descendig Order.


Question: How to make unique key in MongoDB?
db.users.ensureIndex({"username":1},{unique:true,sparse:true})
Now you can't add duplicate username in users collection.



Question: What is sparse in MongoDB indexing?
Sparse indexes only contain entries for documents that have the indexed field. The index skips over any document that is missing the indexed field. The index is sparse because it does not include all documents of a collection. .


Question: How to create indexing in background process?
db.users.ensureIndex({"title":1},{background:true})



Question: How to create indexing on column which can have duplicate values?
db.users.ensureIndex({"title":1},{dropDups:true})



Question: How can we set index name while creating indexing?
db.users.ensureIndex({"title":1},{name:'bankdb_users_index'})



Question: How to drop an index on single column?
db.users.dropIndex({"title":1})



Question: How to drop all indexes on document?
db.users.dropIndexex()



Question: How to update all index in collection?
db.collection.reIndex()



Question: How to create indexing in Embed document?
db.users.ensureIndex({"profile.city":1})

Search Document From Embed document
db.users.find( { "profile.city" : "newYork" } )



Question: Compare "Multiple collections" vs "Embedded documents"?
  1. No much differences for insertion and updates document.
  2. Separate collections are better when you need to select individual documents and gives more control over querying.
  3. Embedded documents are better when embed document is less OR No More.
  4. Getting record from embedded documents is easy as compare Multiple collections.
  5. Embed document limit is 16MB
Question: What is Relationships in MongoDB?
Relationships denotes how various documents are logically related to each other.


Question: What are different ways to achieve the relationships in MongoDB?
Following are various two Approaches
1) Embedded Approaches 2) Referenced Approaches


Question: Given an example of Embedded?
[
  {
    "_id": ObjectId("52ffc33cd85242f436099901"),
    "contact": "987654321",
    "dob": "01-01-1991",
    "name": "Tom Benzamin",
    "address": [
      {
        "pincode": 123456,
        "city": "Los Angeles",
        "state": "California"
      },
      {       
        "pincode": 456789,
        "city": "Chicago",
        "state": "Illinois"
      }
    ]
  }
]



Question: Given an example of Referenced?
[
  {
    "_id": ObjectId("52ffc33cd85242f436099901"),
    "contact": "987654321",
    "dob": "01-01-1991",
    "name": "Tom Benzamin",
    "address": [
        ObjectId("63ffc4a5d85242602e000000"),
        ObjectId("63ffc4a5d85242602e000001")
    ]
  }
]