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

Thursday 19 September 2019

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();  



Wednesday 18 September 2019

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
}



Monday 16 September 2019

Angularjs listing example with JSON

Angularjs listing example with JSON



[script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"][/script]
[script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.js"][/script]
[style]
    .secdsubmenu{position:absolute; right:22px; top:2px; border:1px solid #eee; background:#fff; z-index:99}
    .secdsubmenu ul {padding:10px; margin:0}
    .secdsubmenu ul li{list-style:none; font-size:13px; color:#333; padding:0; margin:0; white-space:nowrap; border-bottom:1px solid #eee; height:30px; line-height:30px; }
    .secdsubmenu ul li a{color:#333; text-decoration:none}
[/style]
<div ng-app="myAppName" ng-controller="myCtrl">
<div class="inputfield">
<input ng-model="$ctrl.query" placeholder="Search" type="text" />
    </div>
<table border="1" cellpadding="2" cellspacing="0" style="width: 500pxpx;">
        <tbody>
<tr>
            <th>Title <button ng-click="sortBy('Title')">&gt;</button></th>
            <th>Date &amp; Time</th>
            <th>Status</th>
            <th>Action</th>
        </tr>
<tr ng-repeat="x in names| filter:$ctrl.query |  orderBy:Title:reverse">
            <td>{{x.Title}}</td>
            <td>{{x.DateTime}}</td>
            <td>{{x.Status}}</td>

            <td><a href="https://www.blogger.com/blogger.g?blogID=5911253879674558037#" ng-click="mySubmenu = !mySubmenu">...</a>
                <br />
<div class="secdsubmenu" ng-show="mySubmenu">
<ul>
<li><a href="https://www.blogger.com/blogger.g?blogID=5911253879674558037#">Edit</a></li>
<li><a href="https://www.blogger.com/blogger.g?blogID=5911253879674558037#">Delete</a></li>
<li><a href="https://www.blogger.com/blogger.g?blogID=5911253879674558037#">View URL</a></li>
<li><a href="https://www.blogger.com/blogger.g?blogID=5911253879674558037#">Embeded Code</a></li>
</ul>
</div>
</td>
        </tr>
</tbody></table>
</div>
[script]
    var myApp = angular.module('myAppName', ['ngAnimate']);
    myApp.controller('myCtrl', function($scope, $http) {
        $http.get("load_data.php")
                .then(function(response) {
                    $scope.names = response.data.records;
                });
        $scope.mySubmenu = false;

        $scope.Title = 'title';
        $scope.reverse = true;

        $scope.sortBy = function(title) {
            $scope.reverse = ($scope.title === title) ? !$scope.reverse : false;
            $scope.title = title;
        };
    });
[/script]
JSON Data load_data.php
    
{ "records":[ 
{"Title":"Title 1","DateTime":"Jul 29 2016, 01:00 AM","Status":"Completed"}, 
{"Title":"Title 2","DateTime":"Jul 28 2016, 02:00 PM","Status":"Completed"}, 
{"Title":"Title 3","DateTime":"Jul 27 2016, 03:00 AM","Status":"Completed"}, 
{"Title":"Title 4","DateTime":"Jul 26 2016, 04:00 AM","Status":"Completed"}, 
{"Title":"Title 5","DateTime":"Jul 25 2016, 05:00 AM","Status":"Completed"}, 
{"Title":"Title 6","DateTime":"Jul 24 2016, 06:00 AM","Status":"Completed"}, 
{"Title":"Title 7","DateTime":"Jul 23 2016, 09:00 AM","Status":"Completed"},
]}

Wednesday 11 September 2019

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



Tuesday 10 September 2019

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