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

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.


Saturday 28 November 2015

Comparison between MySQL and MongoDB

Comparison between MySQL and MongoDB

Features MySQL MongoDB
Logo


Type of Database? Relational Database Document-oriented database
Initial release 23 May 1995 13 October 2015
Current Stable Version 5.7.18 / 10 April 2017 3.4.5 / 14 June 2017
Written in C/C++ C/C++, JavaScript
Open Source Yes Yes
License GPL (version 2) or proprietary GNU AGPL v3.0 (drivers: Apache license)
Offical Website http://www.mysql.com https://www.mongodb.org
How stored Data In Structed, data is stored in tables. Unstructed, data is stored in Collection in JSON Format.
Terminology Table
Row
Column
Joins
Collection
Document
Field
Embedded documents, linking
Normalization used to minimize data redundancy Normalization is obsolete for MongoDB
Get data from two different tables Joins are used References are used
Transactions vs Atomic Updates MySQL Support No supported
How to get data SQL Query is used you need to used functions with parameter
Security MySQL uses privilege-based security model. MongoDB security features include authentication, authorization and auditing
Select Query
SELECT * FROM users
 WHERE name LIKE "%Web%";
db.books.find({"name": { 
"$regex":  "Web" }});
Insertion Query
INSERT INTO users (user_id, age, status) 
VALUES ("100", 20, "Active")
db.users.insert({  user_id: "100",
  
age: 20,  status: "Active"})
Update Query
UPDATE users SET status = "Active" 
WHERE age > 25
db.users.update( {
age: { $gt: 25 } }, { $set: { 
status: "Active" } }, { multi: true }
)
Insert data Speed Normall Much Faster as compare to MySQL
Best Database for Very-2 Heavy Site Not MongoDB is better
DBA Required Yes, For better performance Not required
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