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

Wednesday 29 July 2020

How do I manage MongoDB connections in a Node.js web application?

How do I manage MongoDB connections in a Node.js web application?

Question: How do I manage MongoDB connections in a Node.js web application?
You need to install mongoose and bluebird module.
Also you must have mongodb install in server, As you need mongodb URL and port on which mongodb running.

Example
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
//mongodb connection with error handing
mongoose.connect(config.MONGO_DB_URL + config.MONGO_DB);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    console.log("MongoDB connected Successfully.!");
});




Question: mongoose - find all documents with IDs listed in array?
var AjaxChatUser = mongoose.model('AjaxChatUser');
AjaxChatUser.find({
    '_id': { $in: [
        mongoose.Types.ObjectId('4ed3ede8844f0f351100000c'),
        mongoose.Types.ObjectId('4ed3f117a844e0471100000d'), 
        mongoose.Types.ObjectId('4ed3f18132f50c491100000e')
    ]}
}, function(err, docs){
     console.log(docs);
});



Question: How to npm install to a specified directory?
Use --prefix option, to installed in specific directory.
Example
npm install --prefix  -g



Question: How to declare multiple module.exports in Node.js?
You can put multiple function inside module.exports.

Example
module.exports = {
    method: function() {},
    otherMethod: function() {},
};


Question: Can we write a JS code that work for both (node and the browser)?
Yes, We can write.
Suppose we have mymodule.js which have following code.
Example of Code
(function(exports){
   exports.test1 = function(){
        return 'this is test1 function.'
    };
   exports.test2 = function(){
        return 'this is test2 function.'
    };

})(typeof exports === 'undefined'? this['mymodule']={}: exports);


In Node (Server side()
var share = require('./mymodule.js');
share.test1();
share.test2();


In Browser (Client side()
//Include the js with script tag
share.test1();
share.test2();




Question: How we can use global variable in Node?
We can use with global.varname
global.version='1022.55';



Question: How we can access static files with express.js in Node?
Use following to set the folder as static so that we can put public files here.
app.use(express.static('public')); //public folder




Thursday 10 October 2019

How to speed up your application with MongoDb?

How to speed up MongoDb?

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


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


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



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



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

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

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



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


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

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

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

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



9) Set Maximum Execution time

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



10) Rebuild Your Indexes

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



Friday 27 September 2019

MongoDB Questions and Answers for beginners

MongoDB Questions and Answers for beginners

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



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



Question: Does MongoDB support foreign key constraints?
No.



Question: Does MongoDB support ACID transaction?
No.



Question: Does MongoDB support Indexes?
Yes.



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



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



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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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



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



Wednesday 25 September 2019

MongoDB indexing and Embed document

MongoDB indexing and Embed document

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


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


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



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


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



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



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



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



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



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



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

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



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


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


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



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



Sunday 22 September 2019

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



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





Monday 9 September 2019

MongoDB update and delete records with examples

MongoDB update and delete records with examples




Question: How to Update Single Record? (Even Multiple Found)
db.players.update({"age":29},{$set:{number:1000}})
It will delete single record.
Output
WriteResult({"nMatched":1,"nUpserted":0,"nModified":1})



Question: How to update Update multiple Record? - 1 way
db.players.update({"age":29},{$set:{number:100}},{multi:true})
It will delete multiple record.
Output
WriteResult({
  "acknowledged": true,
  "matchedCount": 3,
  "modifiedCount": 3
})



Question: How to Update multiple Record? - 2 Way
db.players.updateMany({"age":29},{$set:{number:135}})
Output
WriteResult({
  "acknowledged": true,
  "matchedCount": 3,
  "modifiedCount": 3
})



Question: How to remove a Record(s)?
db.players.remove({"_id" : ObjectId("57ce95da8a12a77c41313adc")});
Will Delete all the record with matched condition.
Output
WriteResult({"nRemoved":1})



Question: How to remove a Record(s) with limit?
db.players.remove({"age":30},2);
It will deleted only 2 records.
Output
WriteResult({"nRemoved":2})



Sunday 8 September 2019

Mongodb index commands with examples

Mongodb index commands with examples

Create OR Use existing Database
use bank;



Create a new collection.
db.createCollection("users");



Add Records in collection.
db.users.insert([{"isActive":false,"balance":"$3,960.64","age":30,"eyeColor":"blue","name":"Dawn Keith","gender":"female","company":"COSMOSIS","email":"dawnkeith@cosmosis.com","phone":"+1 (839) 437-3421","address":"392 Clifford Place, Fontanelle, Arizona, 2687"},{"isActive":false,"balance":"$1,280.14","age":31,"eyeColor":"green","name":"Bettie Eaton","gender":"female","company":"COMTREK","email":"bettieeaton@comtrek.com","phone":"+1 (861) 460-2317","address":"203 Allen Avenue, Elrama, North Carolina, 4453"},{"isActive":true,"balance":"$2,042.37","age":38,"eyeColor":"green","name":"Margie Ayala","gender":"female","company":"VOIPA","email":"margieayala@voipa.com","phone":"+1 (941) 569-2231","address":"111 Schroeders Avenue, Suitland, Louisiana, 7042"},{"isActive":false,"balance":"$3,170.35","age":37,"eyeColor":"blue","name":"Baker Townsend","gender":"male","company":"EVIDENDS","email":"bakertownsend@evidends.com","phone":"+1 (808) 500-2793","address":"190 Just Court, Canoochee, Alabama, 325"}]);



Get all records
db.users.find().pretty();




Analyse the Query
db.users.find().explain("executionStats");



Add Index on collection
db.users.ensureIndex({"age":1});



Get all indexes on collection.
db.users.getIndexes();
Output
[
  {
    "v": 1,
    "key": {
      "_id": 1
    },
    "name": "_id_",
    "ns": "bank.users"
  },
  {
    "v": 1,
    "key": {
      "age": 1
    },
    "name": "age_1",
    "ns": "bank.users"
  }
]



Delete Index on collection.
db.users.dropIndex({"age":1});
Output
{
  "nIndexesWas": 2,
  "ok": 1
}



Drop all indexes.
db.users.dropIndexes();
Output
{
  "nIndexesWas": 1,
  "msg": "non-_id indexes dropped for collection",
  "ok": 1
}



Check Indexes, after droping an index.
db.users.getIndexes();
Output
[
  {
    "v": 1,
    "key": {
      "_id": 1
    },
    "name": "_id_",
    "ns": "bank.users"
  }
]



ReIndex the collecton.
db.users.reIndex()
Output
{
  "nIndexesWas": 1,
  "nIndexes": 1,
  "indexes": [
    {
      "key": {
        "_id": 1
      },
      "name": "_id_",
      "ns": "bank.users"
    }
  ],
  "ok": 1
}



Simple Aggregate Example
db.users.aggregate({$group:{_id:"$age",total:{$sum:1}}});
Output
{
  "_id": 37,
  "total": 1
}{
  "_id": 38,
  "total": 1
}{
  "_id": 31,
  "total": 1
}{
  "_id": 30,
  "total": 2
}



Average Aggregate Example
db.users.aggregate({$group:{_id:"$gender",avgAge:{$avg:"$age"}}});
Output
{
  "_id": "female",
  "avgAge": 32.25
}{
  "_id": "male",
  "avgAge": 37
}



Max Value in Aggregate
db.users.aggregate({$group:{_id:"$gender",richest:{$max:"$balance"}}});
Output
{
  "_id": "female",
  "richest": "$3,960.64"
}{
  "_id": "male",
  "richest": "$3,170.35"
}



Saturday 31 August 2019

MongoDB operators with examples

MongoDB operators with examples

Comparison Query Selectors

$eq  Equal to a specified value.
$gt  Greater than a specified value.
$gte  Greater than or equal to a specified value.
$lt  Less than a specified value.
$lte  Less than or equal to a specified value.
$ne  Not equal to a specified value.
$in  Matches any of the values specified in an array.
$nin  Matches none of the values specified in an array.

Example:
db.mycollectiontest.find('{"likes": {$gt:10}"likes"}'); 


Logical Query Selectors
$or  Joins query clauses with a logical OR Operator.
$and  Joins query clauses with a logical AND Operator.
$not  Inverts the effect of a query expression.
$nor  Joins query clauses with a logical NOR returns.

Example
db.mycollectiontest.find({"likes": {$gt:10}, $or: [{"by": "tutorials point"})


Element Query Selectors
$exists  Matches documents that have the specified field.
$type  Selects documents if a field is of the specified type.



Evalution Query Selector
$mod  Performs a modulo operation.
$regex  Specified regular expression.
$text  Performs text search.
$where  Matches documents that satisfy a JavaScript expression.



Array Query Selector
$all        Matches arrays that contain all elements specified in the query.
$elemMatch Selects documents if element in the array field matches all the specified $elemMatch conditions.
$size       Selects documents if the array field is a specified size.


Field Update Operators
$inc        Increments the value.
$mul        Multiplies the value.
$rename     Renames a field.
$setOnInsert Sets the value of a field if an update results in an insert of a document.
$set  Sets the value of a field in a document.
$unset  Removes the specified field from a document.
$min  Only updates the field if the specified value is less than the existing field value.
$max  Only updates the field if the specified value is greater than the existing field value.
$currentDate  Sets the value of a field to current date, either as a Date or a Timestamp.





Monday 19 August 2019

MongoDb PHP functions Questions and Answers

MongoDb PHP functions Questions and Answers

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



Question: How to select database?
$mongoDbObj = $mongoObj->mydb;



Question: How to create collection?
$collection = $mongoDbObj->createCollection("mycollectiontest");



Question: How to select collection?
$collection= $mongoDbObj->mycollectiontest;



Question: How to insert document in collection?
/* 1 document */
$document = array( 
      "title" => "MongoDB", 
      "description" => "MongoDB database", 
      "likes" => 100,
      "unlikes", 50
   );
   $collection->insert($document);
/* 2 document */
$document = array( 
      "title" => "MongoDB2", 
      "description" => "MongoDB database2", 
      "likes" => 1002,
      "unlikes", 502
   );
   $collection->insert($document); 



Question: How to list all documents?
   $cursor = $collection->find();
   foreach ($cursor as $document) {
      print_r($document);
   }

Output
Array
(
    [_id] => MongoId Object
        (
            [$id] => 57c3e73d9ba8827012000029
        )

    [title] => MongoDB
    [description] => MongoDB database
    [likes] => 100
    [0] => unlikes
    [1] => 50
)
Array
(
    [_id] => MongoId Object
        (
            [$id] => 57c3e7e79ba8821815000029
        )

    [title] => MongoDB2
    [description] => MongoDB database2
    [likes] => 1002
    [0] => unlikes
    [1] => 502
)
Array
(
    [_id] => MongoId Object
        (
            [$id] => 57c3e8fb9ba882181500002a
        )

    [title] => MongoDB2
    [description] => MongoDB database2
    [likes] => 1002
    [0] => unlikes
    [1] => 502
)



Question: How to list all documents (2nd way)?
 $cursor = $mongoObj->mydb->{'mycollectiontest'}->find();
/*$mongoObj is clinet, mydb is database, mydb is collections*/
   foreach ($cursor as $document) {
      print_r($document);
   }



Question: How to list all documents (3rd way)?
$query = array('title' => 'MongoDB');
$cursor = $collection->find($query);
   foreach ($cursor as $document) {
      print_r($document);
   }



Question: How to delete a document?
 $collection->remove(array("title"=>"MongoDB2"));



Question: How to update a document?
  $collection->update(array("title"=>"MongoDB"), 
 array('$set'=>array("description"=>"This is updated description")));



Sunday 23 June 2019

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