Thursday, 31 December 2015

Zend Framework 2 Json Model understanding

Zend Framework 2 Json Model understanding


Question: How to render JSON response?
In controller use, JSONModel
public function indexAction()    {
        $result = new JsonModel(array('data'=>array(
     'key1' => 'value1',
     'key2' => 'value2',
     'key3' => 'value3',
     'key4' => 'value4',
     'key5' => 'value5'
            
        )));

        return $result;
    }

In View file, use following the encode the array.
echo Zend\Json\Json::encode($this->jsonArray, Zend\Json\Json::TYPE_ARRAY);



Question: How to JSON Encode an php object in recursive way?
$arrayData = Zend\Json\Json::encode($phpObject, true);



Question: How to convert XML to JSON?
$jsonContents = Zend\Json\Json::fromXml($xmlStringContents, true);



Question: How to get PHP Array from JSON Encoded string in view file?
$encodedValue='[1,2,3,4,5,6]';
$arrayData = Zend\Json\Json::decode($encodedValue,Zend\Json\Json::TYPE_ARRAY);
print_r($arrayData );die;


Question: How to get PHP Object from JSON Encoded string in view file?
$encodedValue='[1,2,3,4,5,6]';
$arrayData = Zend\Json\Json::decode($encodedValue,Zend\Json\Json::TYPE_OBJECT);
print_r($arrayData );die;



Question: How to display JSON Encoded string in Pretty way?
$encodedValue='[1,2,3,4,5,6]';
$arrayData = Zend\Json\Json::prettyPrint($encodedValue, array("indent" => " "));
print_r($arrayData );die;



Question: How to check Ajax Request OR Not?
if($this->getRequest()->isXmlHttpRequest())){
/** 
This is Ajax Request 
**/
}else{
/** 
This is NOT Ajax Request 
**/
}



Wednesday, 30 December 2015

Zend Framework2 manage layout and view variables from controller

Zend Framework manage layout and view variables from view


Question: How to set variable to layout from controller?
Following are different three ways to set the variable from controller.
First way
public function indexAction(){ 
    $this->layout()->variableName = 'value1';
}

Second way
public function indexAction(){ 
    $this->layout()->setVariable('variableName', 'value2');
}

Third way
    public function indexAction(){ 
    $this->layout()->setVariables(array(
        'variableName1' => 'value1',
        'variableName2'  => 'value2',
    );
}

In layout File, you can access with following way.
$this->variableName1;


Question: How to set variable to view from controller in Zend Framework2
public function indexAction(){ 
return new ViewModel(array(
           'variableName3' => 'value 3',
         ));
}

in layout view, you can access with following way.
$this->$this->variableName2;



Question: How I can get access to my module config from the controller?
public function indexAction(){ 
    $config = $this->getServiceLocator()->get('Config');
}



Question: How to Change layout in the controller in Zend Framework 2.0?
public function indexAction(){ 
    $this->layout('layout/mynewlayout'); /*It will search view/layout/mynewlayout.phtml*/
}



Question: How to disable layout in zend framework 2?
public function indexAction(){ 
    $viewModel = new ViewModel();
    $viewModel->setTerminal(true);
}



Question: How to disable render view in zend framework 2?
public function indexAction()
{ 
    return false;
}




Tuesday, 29 December 2015

Zend Framework 2 get params from URL

Zend Framework 2 get params from URL


Question: How to read the data from php://input?
$content = file_get_contents('php://input');
print_r(json_decode($content));



Question: How to get parameter value from GET without using Params plugin?
$parameterName1=$this->getRequest()->getRequest('parameterName2');
$parameterName2=$this->getRequest()->getRequest('parameterName2','Default Value');



Now with use of params plugins, you can get values easily from all type of request


Question: How to get parameter value from URL?
$parameterName1=$this->params()->fromQuery('parameterName1');
$parameterName2=$this->params()->fromQuery('parameterName2','Default Value');



Question: How to get all parameters value from URL?
$parameterArray=$this->params()->fromQuery();



Question: How to get parameter value from POST?
$parameterName1=$this->params()->fromPost('parameterName1');
$parameterName2=$this->params()->fromPost('parameterName2','Default Value');



Question: How to get all parameters value from POST?
$parameterArray=$this->params()->fromPost();



Question: How to get parameter value from header?
$parameterName1=$this->params()->fromHeader('parameterName1');
$parameterName2=$this->params()->fromHeader('parameterName2','Default Value');



Question: How to get parameter value from uploadedFile?
$parameterName1=$this->params()->fromFiles('parameterName1');
$parameterName2=$this->params()->fromFiles('parameterName2','Default Value');



Question: How to get parameter value from RouteMatch?
$parameterName1=$this->params()->fromRoute('parameterName1');
$parameterName2=$this->fromRoute()->fromFiles('parameterName2','Default Value');



Monday, 28 December 2015

How to enable error reporting in Zend Framework 2?

How to enable error reporting in Zend Framework 2?

Question: How to enable error reporting in Zend Framework 2?
Open index.php in public (at root).
and add following line at the top.
error_reporting(E_ALL);
ini_set("display_errors", 1);



Question: How to enable error reporting in Zend Framework 2 for Development Server only?
Set the different APPLICATION_ENV value for development and production with use of .htaccess. For Example

Add following in .htaccess file in Development Server
SetEnv APPLICATION_ENV development

Add following in .htaccess file in Production Server
SetEnv APPLICATION_ENV production


Add following line in top of public/index.php
 if ($_SERVER['APPLICATION_ENV'] == 'development') {
     error_reporting(E_ALL);
     ini_set("display_errors", 1);
 }else if($_SERVER['APPLICATION_ENV'] == 'production'){
     error_reporting(0);
     ini_set("display_errors", 0);
}



Saturday, 26 December 2015

What is Composer in php? - Manage the Dependencies

What is Composer in php? -  Manage the Dependencies


Question: What is Composer?
Composer is an application-level package manager for the PHP.


Question: Why Composer is used?
  1. Composer provides a standard format for managing dependencies of PHP software.
  2. Composer installs the dependencies libraries.
  3. Composer provides autoload capabilities for libraries.


Question: Where composer is used?
When we need manage the dependencies of PHP application, we can use Composer.


Question: How Composer Works?
It works commond line.


Question: Who developed the Composer?
  1. Nils Adermann.
  2. Jordi Boggiano.
.

Question: What is current stable version of Composer?
1.2.0 / July 18, 2016.


Question: In Which language, It was writeen?
PHP.


Question: What is offical website of Composer?
http://getcomposer.org/


Question: What are System Requirements for compser?
  1. PHP 5.3.2+
  2. Need git, svn or hg repository depend of composer version.


Question: What is command to download the composer?
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('SHA384', 'composer-setup.php') === '544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"
You need curl OR openssl enable for above command.


Question: How to install the composer?
php composer.phar install



Question: How to update the composer?
php composer.phar update



Question: How to check current version of composer?
php composer.phar -V



Question: Can I used composer standard for my new project?
Yes, you can start.


Question: Is it open-source?
Yes, It is open-source.


Question: Give me sample of composer.json file?
{
    "name": "zendframework/skeleton-application",
    "description": "Skeleton Application for ZF2",
    "license": "BSD-3-Clause",
    "keywords": [
        "framework",
        "zf2"
    ],
    "homepage": "http://framework.zend.com/",
    "require": {
        "php": ">=5.3.3",
        "zendframework/zendframework": "2.3.2"
    }
}

Thursday, 24 December 2015

How to install Zend Framework 2 in windows


How to install Zend Framework 2 in windows

  1. Add PHP.exe Path to Your Windows Path Variable.
    Means we need to add php.exe's path to windows path variable So that you can execute php commands.
    (My php.exe Path: E:\wamp\bin\php\php5.4.3)
    Not understand OR any Doubt 
  2. Make sure you have >=PHP5.4 Version.
  3. Now download Zend Framework 2.3.2 From https://github.com/zendframework/ZendSkeletonApplication/releases/tag/release-2.3.2
  4. Unzip this zipped file .
  5. Rename ZendSkeletonApplication to zf2.
  6. Copy this zf2 folder to E:\wamp\www
  7. Login to command prompt & Go to www folder of wamp (Path: E:\wamp\www\zf2)
  8. Now download composer with following command.
    php -r "readfile('https://getcomposer.org/installer');" | php
    If the above fails, enable php_openssl.dll in php.ini & Restart wamp Server.
  9. Now execute following command to install the composer
    php composer.phar install
  10. Apache Setup  (Path: E:\wamp\bin\apache\apache2.2.22\conf\extra)
    <virtualhost> DocumentRoot "D:\wamp\www\zf2\public" ServerName zf2.loc <directory public="" wamp="" www="" zf2=""> Options FollowSymLinks MultiViews AllowOverride All Order allow,deny Allow from all </directory> </virtualhost>
  11. Append following line in host File (Path:C:\Windows\System32\drivers\etc)
    127.0.0.1       zf2.loc
  12. ReStart your wamp Server.
  13. http://zf2.loc in Web Browser

Wednesday, 16 December 2015

EmberJS Interview Questions and Answers

EmberJS Interview Questions and Answers


Question: What is npm install?
NPM is a NodeJS package manager. It is used to install the node programs.


Question: How to install NPM on windows?
Download MSI from https://nodejs.org/download/release/ for 32bit|64bit system.


Question: How to update NPM on windows?
npm install npm
OR
Download Latest MSI from https://nodejs.org/download/release/latest/ for 32bit|64bit system.


Question: How to install Ember using npm?
npm install -g ember-cli



Question: How to get to know the Version of Ember?
ember -v


Question: How to get the Version of node?
node -v


Question: How to create a new project?
ember new my-newproject



Question: How to go inside new project for execute project based commands?
cd my-newproject



Question: What are different commands available in ember-cli?
ember g route about
It will give you list of commands available for Ember.


Question: How to define view.?
Ember.View.create({
   templateName: 'NameOfTemplate',   
});



Question: How to implement IF,ELSE,NOT in ember handlebar?
{{#unless isValid}}
  
{{else}}
    
{{/unless}}



Question: How to add/Delete data in Array?
//In JS
App.obj = Ember.Object.create({
    "things": Ember.A(["Testing1", "Testing2"])
});
App.obj.things.pushObject("3"); // Add data

// HTML + Handlebars
{{#with App.obj}}
    
    {{#each things}}
  • {{this}}
  • {{/each}}
{{/with}}



Question: Explain the core concept of EmberJS
  1. Store: It is central repository and cache of all records available in an application. It can be accessed by controller and admin.
  2. Models: A model is a class which defines the data of properties and behavior.
  3. Records: A record is an instance of a model which contains information that is loaded from a server.
  4. Adapter: It is responsible for translating requested records into the appropriate calls t
  5. Serializer: Translating JSON data into a record object.
  6. Automatic Caching:Used for caching



Question: What is Ember-data?
Ember-Data is a library that retrieve records from a server, store them, update them in the browser and save them back to the Server.


Question: What is Application Template?
Application Template have header, footer and contents which display on page. there can be many Template in one application.


Question: What is ember.mixin class?
Ember.mixin class can create objects, whose functions and properties can be shared among other instances and classes.


Tuesday, 15 December 2015

Basic Ember js Interview Questions and Answers


Basic Ember js Interview Questions and Answers


Question: What is EmberJS?
It is javasScript framework based on Model-view-controller(MVC) and written in javascript. It allows developers to create scalable single-page web applications by incorporating common idioms.
In this, Route is used as model, template as view and controller manipulates the data in the model.


Question: What is old name of EmberJS?
SproutCore MVC framework


Question: In which language, EmberJS is written?
javaScript


Question: When First EmberJS was released?
December 08, 2011


Question: When latest EmberJS was released?
November 16, 2015


Question: What is latest version of EmberJS?
2.2.0


Question: Who created EmberJS?
Yehuda Katz


Question: Is it opensource?
Yes, It is free to use.


Question: What is offical website of EmberJS?
http://emberjs.com/


Question: What are basic models of EmberJS?
  1. Routes: State of application is represented by URL and each URL has a corresponding route object that.
  2. Models: Use to load data from Server.
  3. Templates: This is html of layout.
  4. Components: It is custom tag.
  5. Services: Services are just singleton objects to hold long-lived data such as user sessions



Question: Why I use EmberJS?
  1. Open source JavaScript framework
  2. Flexible framework that embraces the concept of fast web page
  3. It has smaller size as compare to other library
  4. Data binding Support



Question: What are the Features of EmberJS?
  1. Creating reusable modules
  2. Handlebars Templates
  3. Automatice determines the route and controller during declaration of the route resources
  4. Used routes
  5. Extensive view type support.
  6. Easy to configure



Question: List out main components of Ember.js?
  1. Models
  2. The Router
  3. Controllers
  4. Views
  5. Components
  6. Templates
  7. Helpers



Question: What are different template components in Ember.js?
  1. Partial
  2. View
  3. Render
  4. Yield
  5. Outlet


Question: What controller does in Ember.js?
Decorate the model returned by the route.
It can listen to actions performed by users.


Question: Explain what is Ember-data?
It is a library that retrieve records from a server, store, update in the browser and save them back to the server.


Question: How you can define a new ember class?
use extend () method.


Question: What is Enumerables in Ember.js ?
enumerable is any object that contains a number of child objects, and enables you to work with those children using the Ember.


Question: Explain Application Template ?
Application Template is a default template that is used when your application starts.


Question: How you can create instances in Ember.js?
use create() method.


Question: What is Ember.Namespace.Class ?
It is used to define an object which contains other objects and data.


Question: Explain the role of adapter? Adapter queries the back end, each adapter is made up of particular back end.

Monday, 14 December 2015

Express Js Interview Questions and Answers

Express Js Interview Questions and Answers


Question: What is Express Js?
Express JS is a framework which helps to develop web and mobile applications. Its works on nodejs plateform. Its sub part of node.js.



What type of web application can built using Express JS?
you can build single-page, multi-page, and hybrid web applications.



Question: What are core features of Express framework?
  1. Allows to set up middlewares to respond to HTTP Requests
  2. Defines a routing table which can works as per HTTP Method and URL.
  3. Dynamically render HTML Pages


Question: Why I should use Express JS?
Express 3.x is a light-weight web application framework to help organize your web application into an MVC architecture on the server side.



Question: How to install expressjs?
http://expressjs.com/en/starter/installing.html


Question: How to get variables in Express.js in GET Method?
var express = require('express');
var app = express();

app.get('/', function(req, res){
    /* req have all the values **/  
  res.send('id: ' + req.query.id);  
});
app.listen(3000);



Question: How to get POST a query in Express.js?
var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded 
app.use(bodyParser.urlencoded({     // to support URL-encoded 
  extended: true
})); 



Question: How to output pretty html in Express.js?
app.set('view options', { pretty: true }); Question: How to get the full url in Express?
var port = req.app.settings.port || cfg.port;
res.locals.requested_url = req.protocol + '://' + req.host  + ( port == 80 || port == 443 ? '' : ':'+port ) + req.path;



Question: How to remove debugging from an Express app?
var io = require('socket.io').listen(app, { log: false });
io.set('log level', 1); 



Question: How to to 404 errors?
app.get('*', function(req, res){
  res.send('what???', 404);
});



Question: How to download a file?
app.get('/download', function(req, res){
  var file = __dirname + '/download-folder/file.txt';
  res.download(file); 
});



Question: What is the parameter “next” used for in Express?
app.get('/userdetails/:id?', function(req, res, next){
 });

req and res which represent the request and response objects
nextIt passes control to the next matching route.



Friday, 11 December 2015

Hadoop Basic Interview Questions and Answer

Hadoop Basic Interview Questions and Answer



Question: Name fews companies that use Hadoop?
  1. Facebook
  2. Amazon
  3. Twitter
  4. eBay
  5. Adobe
  6. Netflix
  7. Hulu
  8. Rubikloud



Question: Differentiate between Structured and Unstructured data?
Data which are proper categorized and easily search and update is know as Structured data.
Data which are proper un-categorized and can't search and update easily is know as Un-Structured data.


Question: On Which concept the Hadoop framework works?
HDFS: Hadoop Distributed File System is the java based file system for scalable and reliable storage of large datasets. Data in HDFS is stored in the form of blocks and it operates on the Master Slave Architecture.
Hadoop MapReduce:MapReduce distributes the workload into various tasks which runs in parallel. Hadoop jobs perform 2 separate job. The map job breaks down the data sets into key-value pairs or tuples. The reduce job then takes the output of the map job & combines the data tuples in smaller set of tuples. The job is performed after the map job is executed.


Question: What is Hadoop streaming?
Hadoop distribution has a generic programming interface for writing the code in any programming language like PHP, Python, Perl, Ruby etc is know as Hadoop Streaming.


Question: What is block and block scanner in HDFS?
Block: The minimum amount of data that can be read or written is know as "block" (Defualt 64MB).
Block Scanner tracks the list of blocks present on a DataNode and verifies them to find any type of checksum errors.


Question: What is commodity hardware?
Hadoop have thousands of commodity hardware which are inexpensive that do not have high availability. these are used to execute to job.


Can we write MapReduce in other than JAVA Language?
Yes, you can write MapReduce task in other languages like PHP, Perl etc.


Question: What are the primary phases of a Reducer?
  1. Shuffle
  2. Sort
  3. Reduce


Question: What is Big Data?
Big data is too heavy database that exceeds the processing capacity of traditional database systems.


Question: What is NoSQL?
It is non-relational un-structured database.


Question: What problems can Hadoop solve?
It sove following problems.
  1. When database too heavy and exceed its limit.
  2. Reduce the cost of server.



Question:Name the modes in which Hadoop can run?
Hadoop can be run in one of three modes:
  1. Standalone (or local) mode
  2. Pseudo-distributed mode
  3. Fully distributed mode



Question:What is the full form of HDFS?
Hadoop Distributed File System

Question:What is DataNode and Namenode in Hadoop?
Namenode is the node which stores the filesystem metadata.
File maps with block locations are stored in datanode.


Question:What are the Hadoop configuration files?
  1. hdfs-site.xml
  2. core-site.xml
  3. mapred-site.xml



Friday, 4 December 2015

How to install MongoDB install on window 7

How to install MongoDB install on windows 7



Follow the Following Simple Steps.
  1. First, get to know window Version (32bit OR 64 Bit) of your system.

    Get window Version (32bit OR 64 Bit)of your system
  2. Now, download the of  MongoDb as per your system from http://www.mongodb.org/downloads

    For window32, 
    I have download from following links:
    https://www.mongodb.org/dl/win32/i386 (Download Links List)
    http://downloads.mongodb.org/win32/mongodb-win32-i386-3.0.7.zip (Download this one)
  3. un-Zip the downloaded zipped-file.
  4. Copy the unzipped folder and move to c drive:
  5. Now create  location of MongoDb database.
    Lets create folder like below: d:/mongodb/data
  6. Now Execute following command from bin folder of mongodb (path: C:\mongodb-win32-i386-3.0.7\bin) From Command Prompt.
    To Set the database folder path
    mongod.exe --dbpath "d:\mongodb\data"

    MongoDb database setup
  7. Now Execute following commands.
    mongo.exe

    MongoDb start working

  8. Now here you can type mongodb commands.
  9. Now here you can try the commands.
    http://www.web-technology-experts-notes.in/2015/11/mongodb-database-commands-with-examples.html

Thursday, 3 December 2015

MongoDB - Where and Why should we use MongoDb?


MongoDB - Where and Why should we use MongoDb?


Question: What is MongoDB?
MongoDB is a cross-platform document-oriented database which works on concept of collection and document. It is classified as a NoSQL database. Its not relational database.


Question: What is Advantages of MongoDB over RDBMS?
  1. Schema is not required.
  2. No Complex Joins
  3. MongoDB supports dynamic queries on documents using a document-based query language
  4. High Availability
  5. Fast results
  6. Recommened for Heavy Database
  7. DBA not required.



Question: Why should use MongoDB?
  1. Data is stored in JSON FOrmat which is much clear.
  2. Index on any attribute.
  3. Auto-Sharding
  4. Professional Support By MongoDB
  5. In Collection, Two document can have different fields



Question: Where should use MongoDB?
  1. Heavy Database
  2. Content Management and Delivery
  3. DBA not available.
  4. You database wil Grow much more in future.
  5. Your Data is Geographic based



Question: Compare the feature of MongoDB with MySQL?
http://www.web-technology-experts-notes.in/2015/11/mongodb-interview-questions-and-answers.html

Question: Where to download the MongoDB?
https://www.mongodb.org/downloads#production


Wednesday, 2 December 2015

Advance MongoDB Interview Questions and Answer

Advance MongoDB Interview Questions and Answer



Question: What are the Comparison Operators in MongoDB? Compare them with RDBMS?
OperationSyntaxExampleRDBMS Equivalent
Greater Than{<key>:{$gt:<value>}}db.mycollection.find({"likes":{$gt:50}}).pretty()where likes > 50
Greater Than Equals{<key>:{$gte:<value>}}db.mycollection.find({"likes":{$gte:50}}).pretty()where likes >= 50
Equality{<key>:<value>}db.mycollection.find({"by":"web-tech"}).pretty()where by = 'web-tech'
Less Than{<key>:{$lt:<value>}}db.mycollection.find({"likes":{$lt:50}}).pretty()where likes < 50
Less Than Equals{<key>:{$lte:<value>}}db.mycollection.find({"likes":{$lte:50}}).pretty()where likes <= 50
Not Equals{<key>:{$ne:<value>}}db.mycollection.find({"likes":{$ne:50}}).pretty()where likes != 50



Question: What is Aggregation operations in MongoDB?
Aggregation operations are functions which are used to group the results. For Example count(*), sum(*) are aggregate functions in RDBMS.

Following are Aggregation operations in MongoDB
ExpressionDescriptionMongoDB Example
$addToSetInserts the value to an array in the resulting document but does not create duplicates.db.mycollection.aggregate([{$group : {_id : "$by_user", url : {$addToSet : "$url"}}}])
$firstGets the first document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage.db.mycollection.aggregate([{$group : {_id : "$by_user", first_url : {$first : "$url"}}}])
$lastGets the last document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage.db.mycollection.aggregate([{$group : {_id : "$by_user", last_url : {$last : "$url"}}}])
$sumSums up the defined value from all documents.db.mycollection.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : "$likes"}}}])
$avgCalculates the average of all given values from all documents.db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$avg : "$likes"}}}])
$minGets the minimum of the corresponding values from all documents.db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$min : "$likes"}}}])
$maxGets the maximum of the corresponding values from all documents.db.mycollection.aggregate([{$group : {_id : "$by_user", num_tutorial : {$max : "$likes"}}}])
$pushInserts the value to an array in the resulting document.db.mycollection.aggregate([{$group : {_id : "$by_user", url : {$push: "$url"}}}])

For Example:
db.mycollection.find({$or:[{"by":"webtechnology"},{"title": "MongoDB"}]}).pretty()



Question: What is Replication in MongoDB?
Replication is the process of synchronizing data across multiple servers. In this we update the data in all servers.
Replication increase the redundancy and but also increases data availability with multiple copies of data on different database servers.


Question: What is benefits Replication in MongoDB?
  1. To keep your data safe
  2. High availability of data in 24*7*365
  3. No downtime for maintenance
  4. Read scaling (extra copies to read from)
  5. Disaster Recovery
  6. Fast



Question: How to setup the Auto-increment fields (like 1,2,34, etc) for a document?
db.mycollection.insert({_id:"productid",sequence_value:0});

The field sequence_value keeps track of the last value of the sequence.


Question: How to Creating Javascript Function?
function getNextSequenceValue(sequenceName){
   var sequenceDocument = db.counters.findAndModify({
      query:{_id: sequenceName },
      update: {$inc:{sequence_value:1}},
      new:true
   }); 
   return sequenceDocument.sequence_value;
}



Question: What is syntax for update the document?
db.mycollection.update(SELECTIOIN_CRITERIA, UPDATED_DATA)



Question: What is syntax for delete the document?
db.mycollection.remove(DELLETION_CRITTERIA)



Question: What is syntax for delete all the document?
db.mycollection.remove()

In this we will not pass criteria for search.


Question: How to sort a document by title in ascending order?
db.mycollection.find().sort({"title":1})



Question: What is MongoDB Projection?
MongoDB projection meaning is selecting only necessary data rather than selecting whole of the data of a document.


Question: What is Capped collections?
Capped collections are fixed-size circular collections that follow the insertion order to high performance for every action.


Question: How to create Capped Collection?
db.createCollection("mycollection",{capped:true,size:100000})



Question: How to check if collection is Capped OR Not?

db.mycollection.isCapped()



Question: What is GridFS? How it is used?
GridFS is the just specification in MongoDB.
GridFS is used for storing and retrieving large files such as images, audio files, video files etc.


Question: What is Rockmongo?
Rockmongo is a MongoDB administration tool using which you can manage your server, databases, collections, documents, indexes etc.


Tuesday, 1 December 2015

MongoDB Interview Questions and Answer on Database

MongoDB Interview Questions and Answer on Database

Question: What is Relationships in MongoDb?
Relationships in MongoDb represent how various documents are related to each other.
For Example:
There are various documents like user, address, payment details etc.
Connection between these documents know as Relationships.


Question: What is Two type Relationships?
  1. Modeling Embedded Relationships
  2. Modeling Referenced Relationships



Question: What is Modeling Embedded Relationships?
In this Approach, we embed the one document into other.
For Example:
{
   "_id":ObjectId("521234cd85242f436000007"),
   "contact": "987685555555",
   "dob": "01-01-1992",
   "name": "User1",
   "address": [
      {         
         "pincode": 160011,
         "city": "Mohali",
       
      },
      {
         "pincode": 140301,
         "city": "Mohali",
      }
   ]
}

We have added the both address in in user document.


Question: Modeling Referenced Relationships?
In this approach, We add the referenceId instead of whole document, thats why know as Referenced Relationships.
For Eample:
{
   "_id":ObjectId("521234cd85242f436000007"),
   "contact": "987685555555",
   "dob": "01-01-1992",
   "name": "User1",
   "address": [
      ObjectId("521234ce85242f436000001"),
      ObjectId("521234ce85242f436000002")
   ]
}


Above is also know as Manual References because we put the RefereceId static.


Question: What is different between "Manual References" and "DBRefs References"?
Manual References
where you save the _id field of one document in another document as a reference know as Manual References.
Just see the above question for Example.

DBRefs References
References the one document with another using the value of first document's _id field, collection name, and database name.



Question: Explain the DBRefs References in detail?
There are three fields in DBRefs:
$ref: This field specifies the collection of the referenced document.
$id: This field specifies the _id field of the referenced document.
$db: Database name where referenced document lies. This is Optional.
{
   "_id":ObjectId("521234cd85242f436000007"),
   "address": {
   "$ref": "address_home",
   "$id": ObjectId("521234cd85242f436000007"),
   "$db": "webtechnology"},
   "contact": "987685555555",
   "dob": "01-01-1991",
   "name": "web-tech"
} 



Question: What is a Covered Query?
Covered query is a query in which all the "fields of Query" and "fields returned in the query" are same index.
For Example:
{
   "_id":ObjectId("521234cd85242f436000007"),
   "address": {
   "$ref": "address_home",
   "$id": ObjectId("521234cd85242f436000007"),
   "$db": "webtechnology"},
   "contact": "987685555555",
   "dob": "01-01-1991",
   "name": "web-tech"
} 

Add "Index"
db.users.ensureIndex({name:1,usercontact:1})


If we are using below:
db.users.find({name:"web-tech"},{usercontact:"987685555555",_id:0})

This is best example for Covered Query.




Question: How to Analyzing the queries in MongoDB?
$explain: The $explain operator provides information on the query, indexes and other statistics. For analyse the use just add .explain() at the end of query.
db.users.find({name:"web-tech"}).explain()


Question: What is use of $hint operator?
$hint: operator is used to forces the query optimizer to use the specified index to run a query.
It is useful when you want to test performance of a query with different indexes with applying the index in real.
db.users.find({name:"web-tech"}).hint({dob:"01-01-2015"}).explain()



Question: Does MongoDb provides atomic transactions?
Yes, but provides only for single document.
In this way, Either it update all fields or none.
db.myproducts.findAndModify({ 
   query:{_id:2,product_available:{$gt:0}}, 
   update:{ 
      $inc:{product_available:-1}, 
      $push:{product_bought_by:{customer:"webtech",date:"19-Jan-2014"}} 
   }    
})



Question: How to add index on document?
db.users.ensureIndex({"dob":1})




Question: How to add index on sub document?
db.users.ensureIndex({"address.city":1,"address.state":1})