Showing posts with label MongoDB. Show all posts
Showing posts with label MongoDB. Show all posts

Friday 7 July 2017

Mongoose iterate records over results using async module

Mongoose iterate records over results using callback functions

Download the async module in nodeJs Project?
npm install async --save



Inculude the module in NodeJS?
async= require('async');



Following are code snippet example which demostrate, how to update the listing?
app.get("get_chat_messages", function(req, res) {
    var vid = req.query.vid;
    
    //Get the records from mongoose
    AjaxChatMessage.find({vid: vid}, function(err, items) {

    //initalize vars
    var index
    var results={}

    //include the module
    async= require('async');

    //iterate records
   async.each(items,     
     function(item, callback){  
         index=items.indexOf(item);
         results[index]={};
         results[index].text=item.text;
         results[index].vid=item.vid;
         results[index].user_display_name=item.user_display_name;
         results[index].id=item.id;
         results[index].photo=item.user.photo;
         results[index].logintype=item.user.logintype;
         
       if((items.indexOf(item)+1)==items.length){
           res.send(results);
       }
     });
     
    }).sort({id: 1}).populate('user');
}



Monday 5 June 2017

Mongoose Tutorial - listing records, Add Record, update record and delete record

mongoose tutorial - listing records, Add Record, update record  and delete record

Question: How to install the mongoose?
npm install mongoose



Question: How to update the mongoose?
npm update mongoose



Question: How to Start the mongoose?
Include the mongoose in the project
var mongoose = require('mongoose');

Make the Db connection with mongodb
mongoose.connect('mongodb://localhost:27017/test');
var db = mongoose.connection;

Check the Error OR Success on Db Connection
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
   console.log("MongoDB connected Successfully.!");
});  




Question: How to Create Model with mongoose?
Here we have set the two fields only, you can add more if required.
var TodoSchema = mongoose.Schema({
  id: String, //datatype is string
  name: String, //datatype is string          
});       
var Todo = mongoose.model('Todo', TodoSchema);

In mongoose.model, the first argument is the singular name of the collection.
Mongoose automatically looks for the plural version with lowercase of your model name.
means for Todo, it will look todos.



Question: How to set unique key for a field?
var TodoSchema = mongoose.Schema({
  id: { type: Number, unique: true}, 
  name: String, //datatype is string          
});



Question: How to set unique key and required for a field?
var TodoSchema = mongoose.Schema({
  id: { type: Number, unique: true }, 
  email: { type: String, unique: true, required:true }, 
  name: String, //datatype is string          
});



Question: How to list the records from mongodb?
var cursor = Todo.find({ }).cursor();
cursor.on('data', function(doc) {
    jsonData[doc.id] = doc.name;  
});
cursor.on('close', function() {
    console.log(jsonData);                   
});



Question: How to save the record?
var TodoDetails = new Todo({ id: "10",name:"this id test message"});
TodoDetails.save(function (err) {if (err) console.log ('Error on save!')});        



Question: How to update the record?
 Todo.update({id: "10" }, { $set: { name: "this is update message" }}, {}, function(){
             console.log("Update the records successfully");
        })



Question: How to delete the record?
    Todo.find({ id:"10" }).remove( function(){
     console.log("Record deleted successfully");
    }); 



Question: How to delete the document and check is it deleted?
Todo.find({ id:"10" }).remove( function(err, effectedRows){
    if(err){
         console.log("Unable to delete the record");
    }
    if(effectedRows.n==0){
        console.log("Zero Record deleted");
    }else{
        console.log("Record deleted successfully");
    }
     
 }); 



Question: What are the difference between mongoose.model and mongoose.Schema?
Model is an object that gives you easy access to a collection, allowing you to query the collection and use the Schema to validate any documents you save to that collection. It is created by combining a Schema, a Connection, and a collection name.

Schema is an object that defines the structure of the documents that will be stored.
it enables you to define types and validators for all data.



Question: How to get first record(s) from listing?
Todo.findOne({ 'name': 'kumar' }, 'id', function (err, person) {
  if (err) return handleError(err);
    console.log(person);          

})        



Question: How to fetch specific column?
  Todo.find({ 'name': 'kumar' }, 'id name', function (err, person) {
          if (err) return handleError(err);
            //console.log(person);          
             res.send(person);
        })



Question: How to limit the number of records?
You can use limit method.
Todo.find({}, 'id name', function (err, person) {
  if (err) return handleError(err);
    console.log(person);          
     
}).limit(3);



Question: How to get listing by name in ascending order?
You can use sort method, -1 means descending order, 1 means ascending order.
Todo.find({}, 'id name', function (err, person) {
  if (err) return handleError(err);
    console.log(person);          
     
}).limit(3).sort({ name: -1 });



Question: How to use "in" in where clause?
Todo.find({ name: { $in: ['arun', 'gupta']}, 'id name', function (err, person) {
  if (err) return handleError(err);
    console.log(person);          
     
}).limit(3).sort({ name: -1 });



Question: Give full Query example?
Todo.find({ 
    occupation: /host/,
    'name.last': 'Ghost',
    age: { $gt: 17, $lt: 66 },
    name: { $in: ['technology', 'web'] }

}, 'id name', function (err, person) {
  if (err) return handleError(err);
    //Here will be display all the records
    console.log(person);               
}).limit(3).sort({ name: -1 });




Question: How to create custom function in mongoose.model?
In schema/Model file (Create a custom function)
var TodoSchema = mongoose.Schema({
  id: { type: Number, unique: true}, 
  name: String, //datatype is string          
});
TodoSchema.statics.findByIdTest = function (todoId,cb) {
  return this.model('Todo').find({ id: todoId }, cb);
};

How to use controller file.
Todo.findByIdTest(2677,function(error, data){
    console.log(data);    
});




Tuesday 30 May 2017

What is mongoose? How to use mongoose with nodejs for mongodb?

What is mongoose? How to use mongoose with nodejs for mongodb?
 How to use mongoose with nodejs for mongodb?

Question: What is mongoose in node js?
mongoose is an object modeling package for Node that essentially works like an ORM.


Question: How to install mongoose in node js?
npm install mongoose



Question: What is the --save option for npm install?
When we do "npm install", then it install the modules.
If we need to update the version of module in package.json, then we have to do it manually.
BUT when we do "npm install --save", then it install the modules and update the package.json automatically.


Question: What is difference between dependencies and devDependencies?
dependencies are modules your project depends on, devDependencies are modules you use to develop your project.

Examples of dependencies are request, through2 and concat-stream.
Examples of devDependencies are grunt, mocha, eslint, tape, and browserify.


Question: How to connect to MongoDB database?
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mongodb');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
   console.log("MongoDB connected Successfully.!");
});


Question: How to define the Schema in mongoose?
var userSchema = mongoose.Schema({
  name: String, //datatype is string
  username: { type: String, required: true, unique: true }, //type is string and its required field and its unique
  password: { type: String, required: true },
  admin: Boolean,
  location: String,  
  created_at: Date //datatype of date  
});



Question: How to compile the Schema with model?
var User = mongoose.model('User', userSchema);
module.exports = User;
Here User inside "mongoose.model" is a User model, where all the data will be managed.
var User is an Model Object which will be used to process on the document.



Question: What are different type of data types in mongodb?
String
Number
Date
Buffer
Boolean
Mixed
ObjectId
Array


Question: How to add a record in document with model?
var userDetails = new User({ name: 'Test user',username:'testuser',password:'test12@',location:'mohali' });
userDetails.save(function (err) {if (err) console.log ('Error on save!')});
console.log(userDetails); 



Question: How to add a record in document with model with FULL CODE?
//include the js
var mongoose = require('mongoose');

//database connection
mongoose.connect('mongodb://localhost:27017/mongodb');

//Create schema
var userSchema = mongoose.Schema({
  name: String, //datatype is string
  username: { type: String, required: true, unique: true }, //type is string and its required field and its unique
  password: { type: String, required: true },
  admin: Boolean,
  location: String,  
  created_at: Date //datatype of date  
});

//create User Object
var User = mongoose.model('User', userSchema);

//Save User details in database
var userDetails = new User({ name: 'Test user',username:'testuser',password:'test12@',location:'mohali' });
userDetails.save(function (err) {if (err) console.log ('Error on save!')});
console.log(userDetails);



Question: How to fetch all records?
User.find({}, function(err, users) {
  if (err) {throw err;}
  console.log(users);
});



Question: How to fetch one record?
User.find({ username: 'testuser' }, function(err, user) {
  if (err) throw err;

  // object of the user
  console.log(user);
});



Question: How to update record?
        User.update({username: 'testuser' }, { $set: { name: "New name" }}, {}, function(){
            //here comes after update the record
        })



Question: How to delete record?
  User.find({ username: 'testuser'  }).remove( function(){
  //write here your code after delete
 }); 



Wednesday 22 March 2017

Express js Interview questions and answers

Express js Interview questions and answers

Question: How to install express js in node?
use following command to install express js.
npm install express



Question: How to use express js in node?
use require to include express module.
var app = require('express')();



Question: How to use handle get request in express Js?
/*Include require module*/
var app = require('express')();
var http = require('http').Server(app);

app.get('/', function (req, res) {
   console.log("Got a GET request for the homepage"); //Shown in console
   res.send('This is GET Method for Homepage'); //Display as response
})

/*Start listing 8080 port*/
http.listen('8080', function() {
    console.log('listening on *:8080');
});



Question: How to use handle post request in express Js?
/*Include require module*/
var app = require('express')();
var http = require('http').Server(app);

app.post('/user_list', function (req, res) {
   console.log("Got a POST request for the user_list URL"); //Shown in console
   res.send('This is POST Method for user_list URL');//Display as response
})

/*Start listing 8080 port*/
http.listen('8080', function() {
    console.log('listening on *:8080');
});



Question: How to use handle GET/POST request for same URL expressJs?
/*Include require module*/
var app = require('express')();
var http = require('http').Server(app);

//This is POST Request
app.post('/add_user', function (req, res) {
   console.log("Got a POST request for the add_user URL"); //Shown in console
   res.send('This is POST Method for add_user URL');//Display as response
})

//This is Get Request
app.get('/user_list', function (req, res) {
   console.log("Got a GET request for the user_list URL"); //Shown in console
   res.send('This is GET Method for user_list URL');//Display as response
})

/*Start listing 8080 port*/
http.listen('8080', function() {
    console.log('listening on *:8080');
});



Question: How to use handle GET request for all URL start with ab* ?
app.get('/ab*', function(req, res) {   
   console.log("Got a GET request for /ab*");
   res.send('Page Regex Match');
})
Question: How to send Server call in Node?
Install the "request" module with following command.
npm install request

Include the request module in page, and send the request to server.
request = require('request');
request( "http://exmaple.com:8081:/users/add/?n=test&p=2277585&email=test@gmail.com", function(err, res, body) {                    
          console.log(res);
          console.log(body);
      });




Question: How to post data and get in express Js?
HTML Code

<form action="http://example.com:8081/register" method="GET">
Name: <input name="name" type="text" />  <br />
Email: <input name="email" type="text" />
         Phone: <input name="phone" type="text" />
         <input type="submit" value="Submit" />
      </form>


Express JS Code
app.get('/register', function (req, res) {   
   response = {
      name:req.query.name,
      email:req.query.email
      phone:req.query.phone
   };
   console.log(response);
   res.end(JSON.stringify(response));
})



Question: How to get cookie in Express js?
Install the "cookie-parser" module with following command.
npm install cookie-parser

Include the cookie-parser, in node.
app.get('/', function(req, res) {
   console.log("Cookies: ", req.cookies)
})


Question: How Static Files works in Express js?
Static files are images/videos/css/js etc.
For this, first you need to set the folder path using "express.static" method. See Example
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/', function (req, res) {
   res.send('Hello ');
});
var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port
})



Question: How to upload images in Express js?
HTML Code

<form action="http://example.com:8081/file_upload" enctype="multipart/form-data" method="POST">
<input name="file" size="50" type="file" />         
         <input type="submit" value="Submit" />
      </form>

ExpressJS Code
var fs = require("fs");
var express = require('express');
var app = express();
var fs = require("fs");

app.post('/file_upload', function (req, res) {
   console.log(req.files.file.name);   
   var destinationFile = __dirname + "/images/" + req.files.file.name;
   
   fs.readFile( req.files.file.path, function (err, data) {
      fs.writeFile(destinationFile, data, function (err) {
         if( err ){
            console.log( err );
            }else{
               response = {
                  message:'File uploaded successfully in '+destinationFile,
                  filename:req.files.file.name
               };
            }
         //console.log( response );
         res.end( JSON.stringify( response ) );
      });
   });
})



Question: What are different methods in REST API?
  1. GET : Used to read.
  2. POST: Used to update.
  3. PUT: Used to create.
  4. DELETE: Used to delete



Question: How to setup the images and access them?
Add Following code in my server.js (OR main file).
app.use(express.static('public'))
Now, you can add images in public folder and can access like below:
http://localhost:3000/1.jpg
http://localhost:3000/2.jpg
http://localhost:3000/3.jpg



Question: How to do increment the value by 1?
 User.update({id: 100}, {$inc: { views: 1 }}).limit(1).exec();



Question: How to do decrement the value by 1?
 User.update({id: 100}, {$inc: { views: -1 }}).limit(1).exec();




Thursday 1 September 2016

MongoDB Interview Questions and Answer for 1 Year Experienced

MongoDB Interview Questions and Answer for 1 Year Experienced

Question: Which field is Default Primary Key in MongoDB?
_id
_id is a 12 bytes hexadecimal number which is unique in every document(record).
Formation of 12 Bytes
4 bytes (for the current timestamp) + 3 bytes (for machine id) + 2 (bytes for process id) + 3 (increment value).


Question: Can we store Regular expression in MongoDB?
Yes, We can do.
For this there is data type i.e Regular expression.


Question: How to store array in MongoDB?
Yes, We can do.
db.mycollectiontest.insert(
{
   "_id": ObjectId(7df78ad8902c), 
   "url": "http://www.example.com",
   "tags": ["mongodb", "database", "NoSQL"],   
})



Question: What is syntax to update the document in collection?
db.collectiontest.update(SELECTIOIN_CRITERIA, UPDATED_DATA)



Question: How to remove one document in collection?
db.collectiontest.remove({'title':'title'},1)



Question: How to remove document based on search criteria?
db.collectiontest.remove({'title':'title'})



Question: How to use limit with search?
db.collectiontest.find({},{"title":1,_id:0}).limit(2)



Question: How to sort the documents?
->sort({"title":-1});



1: Ascending Order
-1: Descending Order



Question: What is Replication in MongoDB?
Replication is the process of synchronizing data across multiple servers.
Replication increases data availability with multiple copies of data on different database servers.


Question: How replication works in MongoDB?
A replica set is a "group of mongod instances" that host the same data set.
In a replica set one node is primary node and remaining nodes are secondary.
In a replica one node is primary node that receives all write operations.
All data replicates from primary to secondary node.


Question: What is Sharding?
Sharding is the process of storing data records across multiple machines to meeting the demands of data growth.


Question: What is Map-reduce?
Map-reduce is a data processing paradigm for condensing large volumes of data into useful aggregated results.


Question: What is a Covered Query?
It is query in which all the fields in the query are part of an index and all the fields returned in the query are in the same index.


Question: How to get new id of inserted New document?
$db->mycollectiontest->insert($data);
$newDocID = $data['_id']; 



Question: How to Find a document with ObjectID in mongoDB?
$item = $collection->findOne(array(
    '_id' => new MongoId('4e49fd8269cb898c0a000000')));



Question: What is use of $explain operator in mongoDB?
$explain operator provides statistics on the query.
Use of query
db.mycollectiontest.find({gender:"F"},{user_name:1}).explain()



Question: How to Create New ObjectId in mongoDB?
newObjectId = ObjectId()



Question: How to ObjectId to String in mongoDB?
newObjectId.str



Question: What is use of $hint operator in mongoDB?
$hint operator forces the query to use the specified index to run a query.
Use of query
db.mycollectiontest.find({gender:"F"},{user_name:1}).hint({gender:1,user_name:1})



Question: What are the Limitations of Indexing?
  1. A collection cannot have more than 64 indexes.
  2. The length of the index name cannot be longer than 125 characters
  3. A compound index can have maximum 31 fields indexed



Friday 26 August 2016

How to Configure MongoDB with PHP for WampServer on Windows

How to Configure MongoDB with PHP for WampServer on Windows

Follow the below simple steps to configure Mongodb with PHP.



Question: How to connect MongoDb Drivers with PHP?
$m = new MongoClient();



Monday 22 August 2016

MongoDb Technical Interview Questions and Answers

MongoDb Technical Interview Questions and Answers

Question: What is MongoDb in technical terms?
MongoDb is No-SQL database. MongoDb is document oriented means store data in JSON Format called BSON. Designed with High Scalability.


Question: What is Replication?
Replication is the process of synchronizing data across multiple servers. It provides redundancy and increases data availability with multiple copies of data on different database servers.


Question: What are benefits of Replication?
  1. (24*7) availability of data
  2. Disaster Recovery
  3. No downtime for maintenance
Question: What is data warehouse?
A data warehouse is a relational database that is designed for query and analysis rather than for processing. It usually contains historical data derived from transaction data. It separates analysis workload from transaction workload and enables an organization to consolidate data from several sources.


Question: What is auto sharding in MongoDB?
Sharding is a method for distributing data across multiple machines. MongoDB uses sharding to support deployments with very large data sets and high throughput operations.


Question: Why sharding used in MongoDB?
  1. In replication all writes go to master node
  2. Latency sensitive queries still go to master
  3. Memory can't be large enough when active dataset is big
  4. Local Disk is not big enough
  5. Vertical scaling is too expensive



Question: What are data type support by MongoDB?
String : This is most commonly used datatype to store the data.
Integer : This type is used to store a numerical value. Integer can be 32 bit or 64 bit depending upon your server.
Boolean : Store a boolean (true/ false) value.
Double : This type is used to store floating values.
Min/ Max keys : This type is used to compare a value against the lowest and highest BSON elements.
Arrays : This type is used to store multiple values into one key.
Timestamp : ctimestamp. This can be handy for recording when a document has been added or modified.
Object : This datatype is used for embedded documents.
Null : This type is used to store a Null value.
Symbol : This datatype is used identically to a string however, it's generally reserved for languages that use a specific symbol type.
Date : This datatype is used to store the current date or time in UNIX time format.
Object ID : This datatype is used to store the document's ID.
Binary data : This datatype is used to store binay data.
Code : This datatype is used to store javascript code into document.
Regular expression : This datatype is used to store regular expression.



Question: How to connect to MongoDb databae through PHP?
$db = new Mongo('mongodb://localhost', array(
    'username' => 'abc',
    'password' => 'abc@123',
    'db'       => 'abc'
));



Question: How to Export database in MongoDb?
mongodump



Question: How to Import database in MongoDb?
mongorestore



Friday 19 August 2016

MongoDB Interview Questions and Answers


 MongoDB Interview Questions and Answers


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


Question: Is it similar to SQL/MySQL?
No, Its totally different from Relational database.


Question: In which language, MongoDB is written?
C/C++, JavaScript


Question: When First MongoDB was released?
2009


Question: When latest MongoDB was released?
13 July 2016


Question: What is latest version of MongoDB?
3.2.8


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


Question: What is offical website of MongoDB?
https://www.mongodb.org


Question: Compare the Terminology of MongoDB and RDBMS?
RDBMS MongoDB
Database Database
Table Collection
Tuple/Row Document
column Field
Table Join Embedded Documents
Primary Key Primary Key (Default key _id provided by mongodb itself)



Question: Compare the Feature of MongoDb?
Feature MySQL MongoDB
Rich Data Model No Yes
Dyamic Schema No Yes
Typed Data Yes Yes
Data Locality No Yes
Field Updates Yes Yes
Easy for Programmers No Yes
Complex Transactions Yes No
Auditing Yes Yes
Auto-Sharding No Yes



Question: What are main feature of MongoDB?
  1. Document-oriented
  2. Ad hoc queries
  3. Indexing
  4. Replication
  5. Load balancing
  6. File storage
  7. Aggregation
  8. Server-side JavaScript execution
  9. Capped collections



Question: What is NoSQL?
It is database which provides a mechanism for storage and retrieval of data that is modeled in means other than the tabular relations used in relational databases like SQL, Oracle, etc.


Question: What are different type of NoSQL?
  1. Key Value
  2. Column Oriented
  3. Document Oriented
  4. Graph



Question: What is Namespace in MongoDB?
A Namespace is the concatenation of the "database name" and "collection name"


Question: Does  MongoDB provide drivers for PHP?
MongoDB provide the drivers for C, C++, C#, Java, Node.js, Perl, PHP, Python, Ruby, Scala, Go and Erlang.


Question: What difference between MongoDB and SQL?
MongoDB allows a highly flexible and scalable document structure.
For e.g. one data document in MongoDB can have five columns &  other one in the same collection can have ten columns. Also, MongoDB database are faster as compared to SQL databases due to efficient indexing and storage techniques.


Question: Does MongoDB support foreign key relationships in MongoDB?
No,Its does not support
But we achieve this concept by embedding one document inside another.


Does MongoDB need lot of RAM?
No, It need less than as compare to other database like SQL,MySQL.
MongoDB dynamically allocates and de-allocates RAM based on the requirements of other processes.


Question: What is the structure of ObjectID in MongoDB?
ObjectID is a 12-byte BSON type with:
4 bytes value representing seconds
3 byte machine identifier
2 byte process id
3 byte counter


Question: How many indexes does MongoDB create by default for a new collection?
By default, MongoDB created the _id collection for every collection.


Question: Explain what are indexes in MongoDB?
Indexes are special structures in MongoDB, which stores a small portion of the data set in an easy to traverse form.


Question: What is sharding in MongoDB?
The procedure of storing data records across multiple machines is referred as Sharding.


Question: How can you see the connection used by Mongos?
To see the connection used by Mongos use db_adminCommand ('connPoolStats');


Question: Explain what is a replica set?
A replica set is a group of mongo instances that host the same data set.


Question: Mention what is the command syntax for inserting a document?
database.collection.insert (document).


Question: Explain what is GridFS in MongoDB?
For storing and retrieving large files such as images, video and audio GridFS is used.


Question: What are alternatives to MongoDB?
Cassandra, CouchDB, Redis, Riak, HBase


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})




Monday 30 November 2015

MongoDB Database Commands with Examples

mongoDB Database Commands with Examples

Question: Expalin the Basic terminology for MongoDB?
RDBMS MongoDB
Database Database
Table Collection
Tuple/Row Document
column Field
Table Join Embedded Documents
Primary Key Primary Key (Default key _id provided by mongodb itself)
Mysqld/Oracle mongod
mysql/sqlplus mongo

Note: # used for commenting.

Question: Create a New database?
use mydb #switched to db mydb



Question: Check which database you are currently using?
use



Question: Display the List of databases?
show dbs #All database will display which have atleast 1 document.



Question: Delete the current database?
db.dropDatabase() #Delete the current used database.



Question: How to create collection for a database?
db.createCollection("mycollection") #create a collection for current selected database.



Question: Display the List of collections in database?
show collections #All collection will display for current database.



Question: How to drop the collection?
db.mycollection.drop() #mycollection collection will be deleted.



Question: How to delete all the records from mongodb ?
db.collection.remove();



Question: How to delete all the records with condition?
db.collection.remove({uid=111});

Will delete all the record where uid=1111


Question: How to insert data(Know as document) into collection?
db.mycollection.insert({
   _id: ObjectId(7df78ad89765),
   title: 'MongoDB Overview',    
   by: 'Web technology',   
   tags: ['mongodb', 'database', 'NoSQL'],   
})
#Single document is added in collection "mycollection" .



Question: How to add multiple document into collection in single command?
db.mycollection.insert({
   {   
   title: 'MongoDB Overview',    
   by: 'Web technology',   
   tags: ['mongodb', 'database', 'NoSQL'],   
   },
 
   {
   title: 'MongoDB Overview2',    
   by: 'Web technology experts notes',   
   tags: ['mongodb', 'database', 'NoSQL' ,'Multiple Record'],   
       
   }
])



Question: What is command for search a document? Give Example?
find() is used to search. For Example

db.mycollection.find()#Search the one document in un structured way .



Question: How to search a document in pretty way (structured way) ? Give Example?
pretty() is used to search in pretty way. For Example

db.mycollection.find({"by":"Web technology"}).pretty()#Search the one document in structured way .



Question: How to search a document with "and condition"?
db.mycollection.find({"by":"Web technology",{"title": "MongoDB Overview"}}).pretty()#Search the one document in structured way .



Question: How to list first 10 document?
db.mycollection.find({"by":"Web technology",{"title": "MongoDB Overview"}}).limit(10).pretty()#Search the 10 document in structured way .



Question: How to get 2nd document?
db.mycollection.find({"by":"Web technology",{"title": "MongoDB Overview"}}).limit(1).skip(1).pretty()#Search the 10 document in structured way .



Question: How to list document with title ascending order?
db.mycollection.find({"by":"Web technology",{"title": "MongoDB Overview"}}).sort({"title":1}).pretty()#Search the in title ascending order.



Question: How to search document in title descending order?
db.mycollection.find({"by":"Web technology",{"title": "MongoDB Overview"}}).sort({"title":-1}).pretty()#Search the in title descending order. 



Question: How to Add indexing?
db.mycollection.ensureIndex({"title":1,"description":-1})#title in ascending order and description in descending order.To create index in descending order you need to use -1. 



Question: How to search a document with "OR condition"?
db.mycollection.find({"by":"Web technology",$or[{"title": "MongoDB Overview"}]}).pretty()#Search the one document in structured way .



Question: How to update a document?
db.mycollection.update({'title':'MongoDB Overview'},{$set:{'title':'MongoDB text'}})#update "MongoDB Overview" with "MongoDB text " .



Question: How to delete a document?
db.mycollection.remove({'title':'MongoDB Overview'})#Delete the record where document is 'MongoDB Overview' .




Find all records
db.mycollection.find();
Display all the records in this collection.



Find all records and display in pretty way
db.mycollection.find().pretty();
Display all the records in this collection but presentable way.



Find all records with single condition (Age: 29)
db.mycollection.find({age:29});
Display all the records where age=29.



Find all records with multiple AND condition (Age: 29, Number:17)
db.mycollection.find({age:29, number:17});
Display all the records where age=29 and number=17



Find all records with multiple OR condition (Age: 29 OR Number:17)
db.mycollection.find({$or:[{age:29},{number:17}]});
Display all the records where age=29 OR number=17 (each of one).



Find all records with multiple OR condition (Age>28 OR Number:17)
db.mycollection.find({$or:[{age:{$gt:28}},{number:17}]});
Display all the records where age>29 and number=17



Find all records and display and one display column (name)
db.mycollection.find({},{name:1}).pretty();
Display all the name in this collections.



Find all records and display and two display column (name and number)
db.mycollection.find({},{name:1,number:1}).pretty();
Display all the name and number in this collections.



Limit the number of record
db.mycollection.find().limit(3).pretty();
Display only 3 records.



Display all the records except 1,2,3
db.mycollection.find().skip(3).pretty();
Skip first 3 records.