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

Friday, 23 June 2017

Mongodb Data Model Design - Embedded data model & Reference data model

Mongodb Data Model Design - Embedded data model & Reference  data model

Question: What is Data Model Design?
Data modeling is first step in database design and object-oriented programming as the designers. It start from conceptual model to logical model to physical schema.


Question: What are different type of Data Model Design?
  1. Embedded Data Models
  2. Reference Data Models



Question: What is Embedded Data Model?
In Embedded Data Model, we store all releated in single document.
For example:
there is a user with name of salman and he has multiple address in different countries.
In this Embedded model, we store the address along with his details. means address and user details in single document.


Question: Give example of embedded Data Model?
One user 'Salman" have multiple address (2 address).
{
  name: 'Salman',
  ssn: '123-456-7890',
  addresses: [
    {
      street: '123 Sesame St',
      city: 'jaipur',
      cc: 'IN'
    },
    {
      street: '123 Avenue Q',
      city: 'New York',
      cc: 'USA'
    }
  ]
}



Question: Where embedded Data Model are good to used?
  1. Data that does not change regularly
  2. Document that grow by a small amount
  3. Data that you'll often need to perform ascending query to fetch
  4. Fast reading speed



Question: What is Normalized Data Models OR Reference Data Model?
In Normalized Data model, we store the user information in multiple collections.
For example,
Single user have multiple address.
Store the user details in user collections.
Store the user address in address collections.
in address collection, we set the reference to user collection.


Question: Give example of Normalized Data Models OR Reference Data Model?
One user 'Salman" have multiple address (2 address).
User collection
{
  id: 100
  name: 'Salman',
  ssn: '123-456-7890',
  
}

User's address collection
 {
      street: '123 Sesame St',
      city: 'jaipur',
      cc: 'IN',
      user_id:100
    }
 {
      street: '123 Avenue Q',
      city: 'New York',
      cc: 'USA',
     user_id:100
}



Question: Where Reference Data Model are good to used?
  1. Large sub documents
  2. When immediate consistency is necessary
  3. Document grow with a large amount
  4. Fast write speed



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:'[email protected]',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:'[email protected]',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 protected]", 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();




Monday, 10 October 2016

How to speed up 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.



Wednesday, 28 September 2016

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



Tuesday, 27 September 2016

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



Thursday, 22 September 2016

MongoDB Interview Question And Answers for 1 Year Experience

MongoDB Interview Question And Answers for 1 Year Experience

Question: How do I query mongodb with like ?
Following are few example of like as compare to SQL Query
/*select * from users where name like "%B%";*/
db.users.find({name: /B/});

/*select * from users where name like "B%"; */
db.users.find({name: /^B/});

/*select * from users where name like "%B"; */
db.users.find({name: /B$/});



Question: How to execute case in sensitive query?
/*select * from users where name like "%B%" OR like "%b%"; */
db.users.find({name: /b/i});



Question: How to list all collections in the mongoDB?
Following are three different methods.
db.getCollectionNames()

show collections

show tables




Question: Pretty print in MongoDB shell?
Normally we use query as below:
db.users.find()

For Pretty display, use like below:
db.users.find().pretty()




Question: How to get the last N records?
db.users.find().sort({_id:-1}).limit(20);
/* -1 means descending order */




Question: How to export collection into CSV?
mongoexport --host localhost --db bank --collection users --csv --out e:/dump/mycsv.csv --fields name,age,gender



Question: How to import into collection from CSV?
mongoimport -d bank -c users --type csv --file e:/dump/mycsv.csv --headerline



Question: How can I rename a field for all documents in MongoDB?
db.students.updateMany( {}, { $rename: { "name": "full_name" } } )



Question: How to store date/time in mongodb
db.users.insert({date: ISODate("2014-02-10T10:50:42.389Z")})



Monday, 19 September 2016

What is sharding in MongoDB?

What is sharding in MongoDB?

Question: What is sharding in MongoDB?
Sharding is a method for distributing data across multiple machines and its MongoDB's approach to meeting the demands of data growth. With increase of the size of the data, a single machine may not be sufficient to store the data OR read and write data. to fix this problem there are two different methods.
Vertical Scaling: Increase the capacity of single server and increase the power.
  • Powerful CPU
  • Increase RAM
  • Increase storage

Horizontal Scaling: dividing the system dataset and load over multiple servers.
We can use multiple server for storing and read/data data.
Using multiple server is lower cost than single machine with high-end hardware but increase the complexity in infrastructure and maintenance for the deployment.


Question: What are MongoDB Query Capabilities?
  • Sorting on one/multiple fields with ascending/descending order.
  • Projection (Retrieving only specified fields from each document in the cursor, not the entire document).
  • Cursor skip() and limit() to easily implement pagination.
  • explain() will return the detail on query will help to optimize the query.
  • aggregate() function used for grouping the records. db.users.aggregate([{$match:{gender:"male"}}, { $group: { _id: null, count: { $sum: 1 } } }]);
  • $match and $unbind function.



Question: How to database details?
db.stats();

Output
{
  "db": "bank",
  "collections": 4,
  "objects": 12,
  "avgObjSize": 245.33333333333334,
  "dataSize": 2944,
  "storageSize": 28672,
  "numExtents": 4,
  "indexes": 2,
  "indexSize": 16352,
  "fileSize": 67108864,
  "nsSizeMB": 16,
  "extentFreeList": {
    "num": 0,
    "totalSize": 0
  },
  "dataFileVersion": {
    "major": 4,
    "minor": 22
  },
  "ok": 1
}



Question: How to collection details?
db.users.stats();
Output
{
  "ns": "bank.users",
  "count": 5,
  "size": 2480,
  "avgObjSize": 496,
  "numExtents": 1,
  "storageSize": 8192,
  "lastExtentSize": 8192,
  "paddingFactor": 1,
  "paddingFactorNote": "paddingFactor is unused and unmaintained in 3.0. It remains hard coded to 1.0 for compatibility only.",
  "userFlags": 1,
  "capped": false,
  "nindexes": 1,
  "totalIndexSize": 8176,
  "indexSizes": {
    "_id_": 8176
  },
  "ok": 1
}



Thursday, 15 September 2016

What is difference between Mongoexport and Mongodump

What is difference between Mongoexport and Mongodump

Question: What is mongodump ?
mongodump is a utility for creating a binary export of the contents of a database. mongodump is used for full backup, partial backup, syncing from production to staging/development, and changing the storage engine.


Question: What are popular options available with mongodump?
--help for Help
--version Version of mongodb
--host Host of database
--version Version of mongodump
--port Specify the port
--username Specify the username
--password Specify the password
--db Specify the database name
--collection Specify the collection name
--query Specify the query
--queryFile Specify the queryFile name
--gzip Compress the output
--out Specify the output folder
--repair Repair the database name



Question: Give few example of mongodump
Run Below command from Administrator window
Backup of all database?
 mongodump 

Backup of Single database?
 mongodump --db bank

Backup of collection?
mongodump --db bank --collection users

How to repair the mongoDB?
mongod --dbpath  "c:/data/db" --repair



Question: What is mongoexport?
mongoexport is used to export the collections data to a JSON or CSV format.


Question: How to export collection using mongoexport?
mongoexport --db bank --collection users --out D:\mm\users.json



Question: How to export collection fields using mongoexport?
mongoexport --db bank --collection users --fields "age,gender,email" --out D:\mm\users_e.json



Question: How to export collection data on behalf of query?
mongoexport --db bank --collection users --query "{'age':'female'}" --out D:\mm\users_e.json



Wednesday, 14 September 2016

MongoDB export and Import databases with Example

MongoDB export and Import databases

Following command will works from Administrator window.

Question: How to backup of all database?
 mongodump 



Question: How to Restore databases
mongorestore


Question: How to backup of Single database?
 mongodump --db bank



Question: How to Restore single database
mongorestore --db bank dump/bank



Question: How to backup of collection?
mongodump --db bank --collection users



Question: How to Restore single database
mongorestore --db testdb --collection users dump/bank/users.bson


Question: How to repair the mongoDB?
mongod --dbpath  "c:/data/db" --repair




Monday, 12 September 2016

MongoDB Cursor with Examples

MongoDB Cursor with Examples

Question: What is cursor in MongoDB?
Cursor is a pointer to the result set of a query.
When you run a query for documents we retrieve a pointer (cursor) to the results instead of all result return.


Question: Give example of Cursor?
var myCursor=db.users.find({"age":30});
while (myCursor.hasNext()) {
   print(tojson(myCursor.next()));
}



Question: How to get the data type of variable?
var data=10;
typeof data;

var data='10';
typeof data;

Output
number
string



Question: What is use of forEach with Cursor?
Iterates the cursor to each document.
Example 1
db.users.find({"age":30}).forEach(printjson);

Example 2
db.users.find({"age":30}).forEach(function(data){
    print(data.name);
});
Output
name1
name2
name3



Question: How to use limit with Query?
 
db.users.find({"age":30}).limit(5).pretty();
Now, cursor will return maximum 5 records.


Question: How to get results in Array instead of JSON?
 
db.users.find({"age":30}).toArray()



Question: How to get number of results from Query?
 
db.users.find({"age":30}).size(); //2



Question: How to sort records by name in Ascending order?
 
 db.users.find({"age":30}).sort({"name":1}).forEach(function(data){print(data.name);});



Question: How to sort records by name in Descending order?
 
 db.users.find({"age":30}).sort({"name":-1}).forEach(function(data){print(data.name);});



Question: How to skip 4th record from query?
 
 db.users.find({"age":30}).skip(4).forEach(function(data){print(data.name);});



Question: How to search records with indexing?
 
 db.users.find({"age":30}).hint({"age":1}).pretty();