- MongoDB:
- Courtesy: MongoDB in 30 Minutes - https://www.youtube.com/watch?v=pWbMrx5rVBE
- MongoDB is a NoSQL database (can be called a document database).
- Data or records are stored as documents; and they use JSON like syntax
- For relational DBs (like MySQL, MSSQL, Oracle, etc) - u need to keep queries ready syntax wise, determine the database schema, table structures, dialects, drivers, etc and what fields u want to use with datatype for each field.
- In NoSQL, you just need to plan out the structure of ur database in your collections, but u dont need to do any predefined structuring b4 u build ur application.
- Biggest adv of NoSQL db or mongodb is scaling. Its really easy to scale compared to sql or relational dbs.
- Also they are much faster in execution than relational dbs.
- When there is a huge load of data, NoSQL is a better option that relational db.
- Download:
- Login to www.mongodb.com - download mongodb community server for windows x64. Based on the license availability/subscription, you can download the mongodb enterprise server.
- For windows 7/windows vista 32-bit, latest version 4.2 is not supported. Need to download version 3.2 or lower for working with Windows 7 32-bit.
- Download links:
- https://www.mongodb.com/download-center/community
- https://www.mongodb.org/dl/win32/i386
- https://www.guru99.com/installation-configuration-mongodb.html#1
- Steps:
- After downloading and installing the mongodb installer (3.2 here), go to the installation dir - C:\Program Files\MongoDB\Server\3.2
- Create two dir - data and log here. Inside data dir, also create a folder called db. In this 'db' folder, all the data will be stored.
- Go to cmd prompt : C:\Program Files\MongoDB\Server\3.2\bin
- Here, first we will run the mongod command and specify the location of the db data that will be stored and the log file location of mongo which will be logged.
- Command:
- mongod --directoryperdb --dbpath "C:\Program Files\MongoDB\Server\3.2\data\db" --logpath "C:\Program Files\MongoDB\Server\3.2\log\mongo.log" --logappend --rest --install
- This will allows us to run mongo as a service.
- You will get output like:
- 2019-09-13T12:17:42.309+0530 I CONTROL [main] ** WARNING: --rest is specified without --httpinterface,
- 2019-09-13T12:17:42.311+0530 I CONTROL [main] ** enabling http interface
- 2019-09-13T12:17:42.312+0530 I CONTROL [main]
- 2019-09-13T12:17:42.312+0530 W CONTROL [main] 32-bit servers don't have journaling enabled by default. Please use --journal if you want durability.
- 2019-09-13T12:17:42.313+0530 I CONTROL [main]
- To start Mongo Server/running mongo as a service:
- Go to cmd prompt : C:\Program Files\MongoDB\Server\3.2\bin
- Hit the command: net stat MongoDB
- You will get output like:
- The MongoDB service is running
- The MongoDB service was started successfully.
- Now mongo is running. You can start working:
- Hit: 'mongo' command to show you the mongo version and open the mongo shell.
- >
- I will brief each command with command name, its usage in comments and itts output in next line
- >show dbs //show databases created on ur local
- local 0.000GB
- >use mycustomers //create new db mycustomers and also switch to it
- switched to db mycustomers
- >db //show current database on which u r working
- mycustomers
- Now before we start inserting data, we will create a user for this database.
- >db.createUser({
- user:"brad",
- pwd:"1234",
- roles:["readWrite","dbAdmin"]
- });
- Successfully added user: { "user" : "brad" , "roles" : [ "readWrite" , "dbAdmin" ] }
- Now, we need to create a collection. Collection is similar to a table if we match it in RDBMS terms.
- So to create a new collection with collection name:
- >db.createCollection('customers');
- { "ok" : 1 }
- >show collections //to see the list of collections
- customers
- Now, if we want to insert a document in that collection:
- >db.customers.insert({first_name:"John", last_name:"Doe"});
- writeResult({ "nInserted" : 1 })
- Now, if u want to see/list the documents in a collection:
- >db.customers.find();
- { "_id" : ObjectId("57cc30a4fcbe31e6b9eb60f7"), "first_name" : "John", "last_name" : "Doe" }
- As u can see above, it automatically adds a unique id value to each document inserted to find the document.
- Now, lets add some more documents:
- You can see below that u can add multiple documents by putting an array in the insert() command:
- Also, in RDBMS, u need to first change the table structure to add a new column, here you can do it on the fly (here, we are adding a new field gender directly in the insert command)
- >db.customers.insert([{first_name:"Steven", last_name:"Smith"}, {first_name:"Joan", last_name:"Johnson", gender:"female"}]);
- BulkWriteResult({
- "writeErrors" : [ ],
- "writeConcernErrors" : [ ],
- "nInserted" : 2,
- "nUpserted" : 0,
- "nMatched" : 0,
- "nModified" : 0,
- "nRemoved" : 0,
- "upserted" : [ ]
- })
- >db.customers.find();
- { "_id" : ObjectId("57cc30a4fcbe31e6b9eb60f7"), "first_name" : "John", "last_name" : "Doe" }
- { "_id" : ObjectId("57cc3125fcbe31e6b9eb60f8"), "first_name" : "Steven", "last_name" : "Smith" }
- { "_id" : ObjectId("57cc3125fcbe31e6b9eb60f9"), "first_name" : "Joan", "last_name" : "Johnson", "gender" : "female" }
- Now, for more data, u might see the above data in jumbled format, so if u want it in a more formatted and readable manner:
- >db.customers.find().pretty();
- {
- "_id" : ObjectId("57cc30a4fcbe31e6b9eb60f7"),
- "first_name" : "John",
- "last_name" : "Doe"
- }
- {
- "_id" : ObjectId("57cc3125fcbe31e6b9eb60f8"),
- "first_name" : "Steven",
- "last_name" : "Smith"
- }
- {
- "_id" : ObjectId("57cc3125fcbe31e6b9eb60f9"),
- "first_name" : "Joan",
- "last_name" : "Johnson",
- "gender" : "female"
- }
- Lets look at updating a field. For example, we want to add gender to John Doe also.
- The first parameter passed in update command is a match. Here its matching with first_name, ideally you should _id field to uniquely update only the specific record. Otherwise, it will update all documents having first_name as John. And the next parameter will be with what we want to replace with.
- >db.customers.update({first_name:"John"}, {first_name:"John", last_name:"Doe", gender:"male"});
- WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
- So, now if you do find, u can see that John Doe has a gender male.
- >db.customers.find().pretty();
- {
- "_id" : ObjectId("57cc30a4fcbe31e6b9eb60f7"),
- "first_name" : "John",
- "last_name" : "Doe",
- "gender" : "male"
- }
- {
- "_id" : ObjectId("57cc3125fcbe31e6b9eb60f8"),
- "first_name" : "Steven",
- "last_name" : "Smith"
- }
- {
- "_id" : ObjectId("57cc3125fcbe31e6b9eb60f9"),
- "first_name" : "Joan",
- "last_name" : "Johnson",
- "gender" : "female"
- }
- Now, while updating John Doe with his gender, in update command, you had to specify first name, last name also along with gender in 2nd parameter to update the gender. If you had specified just gender (without specifying first_name and last_name), it would have replaced the entire string with just gender. So first document/record would then contain only _id and gender, no first_name, no last_name like this:
- >db.customers.update({first_name:"John"}, {gender:"male"});
- WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
- >db.customers.find().pretty();
- {
- "_id" : ObjectId("57cc30a4fcbe31e6b9eb60f7"),
- "gender" : "male"
- }
- {
- "_id" : ObjectId("57cc3125fcbe31e6b9eb60f8"),
- "first_name" : "Steven",
- "last_name" : "Smith"
- }
- {
- "_id" : ObjectId("57cc3125fcbe31e6b9eb60f9"),
- "first_name" : "Joan",
- "last_name" : "Johnson",
- "gender" : "female"
- }
- But, the above update command is just to give example/understanding, we have not fired it actually so that we don't loose data.
- So, to overcome this situation, we have set command:
- Example: we have to add gender to steven smith:
- >db.customers.update({first_name:"Steven"}, {$set:{gender:"male"}});
- WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
- So, now if you do find, u can see that Steven Smith has a gender male, and its previous data is intact.
- >db.customers.find().pretty();
- {
- "_id" : ObjectId("57cc30a4fcbe31e6b9eb60f7"),
- "first_name" : "John",
- "last_name" : "Doe",
- "gender" : "male"
- }
- {
- "_id" : ObjectId("57cc3125fcbe31e6b9eb60f8"),
- "first_name" : "Steven",
- "last_name" : "Smith",
- "gender" : "male"
- }
- {
- "_id" : ObjectId("57cc3125fcbe31e6b9eb60f9"),
- "first_name" : "Joan",
- "last_name" : "Johnson",
- "gender" : "female"
- }
- We also have inc operator to increment numeric values for us.
- So, lets add age to Steven Smith:
- >db.customers.update({first_name:"Steven"}, {$set:{age:45}});
- WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
- >db.customers.find().pretty();
- {
- "_id" : ObjectId("57cc30a4fcbe31e6b9eb60f7"),
- "first_name" : "John",
- "last_name" : "Doe",
- "gender" : "male"
- }
- {
- "_id" : ObjectId("57cc3125fcbe31e6b9eb60f8"),
- "first_name" : "Steven",
- "last_name" : "Smith",
- "gender" : "male",
- "age" : 45
- }
- {
- "_id" : ObjectId("57cc3125fcbe31e6b9eb60f9"),
- "first_name" : "Joan",
- "last_name" : "Johnson",
- "gender" : "female"
- }
- Now, if you want to increment the age of Steven:
- >db.customers.update({first_name:"Steven"}, {$inc:{age:5}});
- WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
- >db.customers.find().pretty();
- {
- "_id" : ObjectId("57cc30a4fcbe31e6b9eb60f7"),
- "first_name" : "John",
- "last_name" : "Doe",
- "gender" : "male"
- }
- {
- "_id" : ObjectId("57cc3125fcbe31e6b9eb60f8"),
- "first_name" : "Steven",
- "last_name" : "Smith",
- "gender" : "male",
- "age" : 50
- }
- {
- "_id" : ObjectId("57cc3125fcbe31e6b9eb60f9"),
- "first_name" : "Joan",
- "last_name" : "Johnson",
- "gender" : "female"
- }
- We also have operator 'unset' if we want to remove a field:
- >db.customers.update({first_name:"Steven"}, {$unset:{age:1}});
- WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
- >db.customers.find().pretty();
- {
- "_id" : ObjectId("57cc30a4fcbe31e6b9eb60f7"),
- "first_name" : "John",
- "last_name" : "Doe",
- "gender" : "male"
- }
- {
- "_id" : ObjectId("57cc3125fcbe31e6b9eb60f8"),
- "first_name" : "Steven",
- "last_name" : "Smith",
- "gender" : "male"
- }
- {
- "_id" : ObjectId("57cc3125fcbe31e6b9eb60f9"),
- "first_name" : "Joan",
- "last_name" : "Johnson",
- "gender" : "female"
- }
- Now, if you try to update some document which is not existing, as expected, it will give output as 0 documents matched and modified:
- >db.customers.update({first_name:"Mary"}, {first_name:"Mary", last_name:"Samson"});
- WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })
- >db.customers.find().pretty();
- {
- "_id" : ObjectId("57cc30a4fcbe31e6b9eb60f7"),
- "first_name" : "John",
- "last_name" : "Doe",
- "gender" : "male"
- }
- {
- "_id" : ObjectId("57cc3125fcbe31e6b9eb60f8"),
- "first_name" : "Steven",
- "last_name" : "Smith",
- "gender" : "male"
- }
- {
- "_id" : ObjectId("57cc3125fcbe31e6b9eb60f9"),
- "first_name" : "Joan",
- "last_name" : "Johnson",
- "gender" : "female"
- }
- But, lets say, if you want to insert this document into customers db, if not found, then you need to add an extra parameter called 'upsert' which will do the thing for you:
- >db.customers.update({first_name:"Mary"}, {first_name:"Mary", last_name:"Samson"}, {upsert: true});
- WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0 , "_id" : ObjectId("57cc3426f7aa7857512f7883") })
- So, now if u do find, Mary has been added and an objectId has been added.
- >db.customers.find().pretty();
- {
- "_id" : ObjectId("57cc30a4fcbe31e6b9eb60f7"),
- "first_name" : "John",
- "last_name" : "Doe",
- "gender" : "male"
- }
- {
- "_id" : ObjectId("57cc3125fcbe31e6b9eb60f8"),
- "first_name" : "Steven",
- "last_name" : "Smith",
- "gender" : "male"
- }
- {
- "_id" : ObjectId("57cc3125fcbe31e6b9eb60f9"),
- "first_name" : "Joan",
- "last_name" : "Johnson",
- "gender" : "female"
- }
- {
- "_id" : ObjectId("57cc3426f7aa7857512f7883"),
- "first_name" : "Mary",
- "last_name" : "Samson"
- }
- Now, you also have rename if you want to rename a field:
- For example, if you want to rename gender to sex:
- >db.customers.update({first_name:"Steven"}, {$rename:{"gender":"sex"}});
- WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
- Now, if you do find, Steven Smith's gender has changed to sex.
- >db.customers.find().pretty();
- {
- "_id" : ObjectId("57cc30a4fcbe31e6b9eb60f7"),
- "first_name" : "John",
- "last_name" : "Doe",
- "gender" : "male"
- }
- {
- "_id" : ObjectId("57cc3125fcbe31e6b9eb60f8"),
- "first_name" : "Steven",
- "last_name" : "Smith",
- "sex" : "male"
- }
- {
- "_id" : ObjectId("57cc3125fcbe31e6b9eb60f9"),
- "first_name" : "Joan",
- "last_name" : "Johnson",
- "gender" : "female"
- }
- {
- "_id" : ObjectId("57cc3426f7aa7857512f7883"),
- "first_name" : "Mary",
- "last_name" : "Samson"
- }
- Now, to remove a document:
- >db.customers.remove({first_name:"Steven"});
- WriteResult({ "nRemoved" : 1 })
- >db.customers.find().pretty();
- {
- "_id" : ObjectId("57cc30a4fcbe31e6b9eb60f7"),
- "first_name" : "John",
- "last_name" : "Doe",
- "gender" : "male"
- }
- {
- "_id" : ObjectId("57cc3125fcbe31e6b9eb60f9"),
- "first_name" : "Joan",
- "last_name" : "Johnson",
- "gender" : "female"
- }
- {
- "_id" : ObjectId("57cc3426f7aa7857512f7883"),
- "first_name" : "Mary",
- "last_name" : "Samson"
- }
- Now, above remove command will delete all documents matching Steven, So for safety, you can add a 'justOne' parameter. It will delete only the first document matching with Steven's name; not all.
- >db.customers.remove({first_name:"Steven"}, {justOne:true});
- Now, we are inserting a few records here to look at the next set of commands:
- >db.customers.insert([
- {
- first_name:"Troy",
- last_name:"Makons",
- gender:"male",
- age:33,
- address:{
- street:"432 Essex st",
- city:"Lawrence",
- state:"MA"
- },
- memberships:["mem1","mem2"],
- balance:125.32
- },
- {
- first_name:"William",
- last_name:"Jackson",
- gender:"male",
- age:43,
- address:{
- street:"11 Albany st",
- city:"Boston",
- state:"MA"
- },
- memberships:["mem1"],
- balance:333.23
- },
- {
- first_name:"Sharon",
- last_name:"Thompson",
- gender:"female",
- age:35,
- address:{
- street:"19 Willis st",
- city:"Worchester",
- state:"MA"
- },
- memberships:["mem1","mem2"],
- balance:99.99
- }
- ]);
- BulkWriteResult({
- "writeErrors" : [ ],
- "writeConcernErrors" : [ ],
- "nInserted" : 3,
- "nUpserted" : 0,
- "nMatched" : 0,
- "nModified" : 0,
- "nRemoved" : 0,
- "upserted" : [ ]
- })
- Now, if we want to find Sharon out of the above documents,
- >db.customers.find({first_name:"Sharon"});
- { "_id" : ObjectId("57cc3803fcbe31e69beb60fe"), "first_name" : "Sharon", "last_name" : "Thompson" , "gender" : "female" , "age" : 35 , "address" : {"street" : "19 Willis st", "city" : "Worchester" , "state" : "MA"} , "memberships" : ["mem1" , "mem2"] , "balance" : 99.99 }
- To find Sharon and Troy, we will use the 'or' operator:
- >db.customers.find({$or:[{first_name:"Sharon"},{first_name:"Troy"}]});
- { "_id" : ObjectId("57cc3803fcbe31e69beb60fa"), "first_name" : "Troy", "last_name" : "Makons" , "gender" : "male" , "age" : 33 , "address" : {"street" : "432 Essex st", "city" : "Lawrence" , "state" : "MA"} , "memberships" : ["mem1" , "mem2"] , "balance" : 125.32 }
- { "_id" : ObjectId("57cc3803fcbe31e69beb60fe"), "first_name" : "Sharon", "last_name" : "Thompson" , "gender" : "female" , "age" : 35 , "address" : {"street" : "19 Willis st", "city" : "Worchester" , "state" : "MA"} , "memberships" : ["mem1" , "mem2"] , "balance" : 99.99 }
- To find multiple results which matches various documents, we will find based on gender
- >db.customers.find({gender:"male"});
- Output will be list of all males matched
- Also, we can use greater than or less than ($gt is greater than , $lt is lesser than). Example: To find everyone whose age < 40.
- >db.customers.find({age:{$lt:40}});
- { "_id" : ObjectId("57cc3803fcbe31e69beb60fa"), "first_name" : "Troy", "last_name" : "Makons" , "gender" : "male" , "age" : 33 , "address" : {"street" : "432 Essex st", "city" : "Lawrence" , "state" : "MA"} , "memberships" : ["mem1" , "mem2"] , "balance" : 125.32 }
- { "_id" : ObjectId("57cc3803fcbe31e69beb60fe"), "first_name" : "Sharon", "last_name" : "Thompson" , "gender" : "female" , "age" : 35 , "address" : {"street" : "19 Willis st", "city" : "Worchester" , "state" : "MA"} , "memberships" : ["mem1" , "mem2"] , "balance" : 99.99 }
- For formatted output, just append pretty():
- >db.customers.find({gender:"male"}).pretty();
- We also have $gte - greater than or equal to / $lte - lesser than or equal to
- Now, we want everyone who lives in the city of Boston:
- >db.customers.find({"address.city":"Boston"});
- { "_id" : ObjectId("57cc3803fcbe31e69beb60fd"), "first_name" : "William", "last_name" : "Jackson" , "gender" : "male" , "age" : 43 , "address" : {"street" : "11 Albany st", "city" : "Boston" , "state" : "MA"} , "memberships" : ["mem1"] , "balance" : 333.33 }
- To find memberships:
- >db.customers.find({memberships:"mem1"});
- { "_id" : ObjectId("57cc3803fcbe31e69beb60fa"), "first_name" : "Troy", "last_name" : "Makons" , "gender" : "male" , "age" : 33 , "address" : {"street" : "432 Essex st", "city" : "Lawrence" , "state" : "MA"} , "memberships" : ["mem1" , "mem2"] , "balance" : 125.32 }
- { "_id" : ObjectId("57cc3803fcbe31e69beb60fd"), "first_name" : "William", "last_name" : "Jackson" , "gender" : "male" , "age" : 43 , "address" : {"street" : "11 Albany st", "city" : "Boston" , "state" : "MA"} , "memberships" : ["mem1"] , "balance" : 333.33 }
- { "_id" : ObjectId("57cc3803fcbe31e69beb60fe"), "first_name" : "Sharon", "last_name" : "Thompson" , "gender" : "female" , "age" : 35 , "address" : {"street" : "19 Willis st", "city" : "Worchester" , "state" : "MA"} , "memberships" : ["mem1" , "mem2"] , "balance" : 99.99 }
- Sorting by last_name (setting to 1 means its in ascending order):
- >db.customers.find().sort({last_name:1});
- { "_id" : ObjectId("57cc30a4fcbe31e6b9eb60f7"), "first_name" : "John", "last_name" : "Doe" }
- { "_id" : ObjectId("57cc3803fcbe31e69beb60fd"), "first_name" : "William", "last_name" : "Jackson" , "gender" : "male" , "age" : 43 , "address" : {"street" : "11 Albany st", "city" : "Boston" , "state" : "MA"} , "memberships" : ["mem1"] , "balance" : 333.33 }
- { "_id" : ObjectId("57cc3125fcbe31e6b9eb60f9"), "first_name" : "Joan", "last_name" : "Johnson", "gender" : "female" }
- { "_id" : ObjectId("57cc3803fcbe31e69beb60fa"), "first_name" : "Troy", "last_name" : "Makons" , "gender" : "male" , "age" : 33 , "address" : {"street" : "432 Essex st", "city" : "Lawrence" , "state" : "MA"} , "memberships" : ["mem1" , "mem2"] , "balance" : 125.32 }
- { "_id" : ObjectId("57cc3426f7aa7857512f7883"), "first_name" : "Mary", "last_name" : "Samson"}
- { "_id" : ObjectId("57cc3803fcbe31e69beb60fe"), "first_name" : "Sharon", "last_name" : "Thompson" , "gender" : "female" , "age" : 35 , "address" : {"street" : "19 Willis st", "city" : "Worchester" , "state" : "MA"} , "memberships" : ["mem1" , "mem2"] , "balance" : 99.99 }
- If we want it in desc order, set to negative (-1)
- >db.customers.find().sort({last_name:-1});
- We can also get the count of documents:
- >db.customers.find().count();
- 8
- We can also put a query in that: For example, we want only those count having gender male:
- >db.customers.find({gender:"male"}).count();
- 4
- We can also limit the count: Here we find all but limit to 4. So first 4 found documents are listed.
- >db.customers.find().limit(4);
- { "_id" : ObjectId("57cc30a4fcbe31e6b9eb60f7"), "first_name" : "John", "last_name" : "Doe" }
- { "_id" : ObjectId("57cc3125fcbe31e6b9eb60f9"), "first_name" : "Joan", "last_name" : "Johnson", "gender" : "female" }
- { "_id" : ObjectId("57cc3426f7aa7857512f7883"), "first_name" : "Mary", "last_name" : "Samson"}
- { "_id" : ObjectId("57cc3803fcbe31e69beb60fa"), "first_name" : "Troy", "last_name" : "Makons" , "gender" : "male" , "age" : 33 , "address" : {"street" : "432 Essex st", "city" : "Lawrence" , "state" : "MA"} , "memberships" : ["mem1" , "mem2"] , "balance" : 125.32 }
- And if you want u can combine the sort with limit:
- >db.customers.find().limit(4).sort({last_name:1});
- { "_id" : ObjectId("57cc30a4fcbe31e6b9eb60f7"), "first_name" : "John", "last_name" : "Doe" }
- { "_id" : ObjectId("57cc3803fcbe31e69beb60fd"), "first_name" : "William", "last_name" : "Jackson" , "gender" : "male" , "age" : 43 , "address" : {"street" : "11 Albany st", "city" : "Boston" , "state" : "MA"} , "memberships" : ["mem1"] , "balance" : 333.33 }
- { "_id" : ObjectId("57cc3125fcbe31e6b9eb60f9"), "first_name" : "Joan", "last_name" : "Johnson", "gender" : "female" }
- { "_id" : ObjectId("57cc3803fcbe31e69beb60fa"), "first_name" : "Troy", "last_name" : "Makons" , "gender" : "male" , "age" : 33 , "address" : {"street" : "432 Essex st", "city" : "Lawrence" , "state" : "MA"} , "memberships" : ["mem1" , "mem2"] , "balance" : 125.32 }
- { "_id" : ObjectId("57cc3426f7aa7857512f7883"), "first_name" : "Mary", "last_name" : "Samson"}
- We can also iterate through documents through forEach:
- Here, we will print the customer name in the loop.
- >db.customers.find().forEach(function(doc){print("Customer Name: "+doc.first_name)});
- Customer Name: John
- Customer Name: Joan
- Customer Name: Mary
- Customer Name: Troy
- Customer Name: Beth
- Customer Name: Timony
- Customer Name: William
- Customer Name: Sharon
More knowledge from tutorails point:
Courtesy: https://www.tutorialspoint.com
Courtesy: https://www.tutorialspoint.com
- MongoDB is written in C++.
- MongoDB is a cross-platform, document oriented database that provides, high performance, high availability, and easy scalability. MongoDB works on concept of collection and document.
- Database is a physical container for collections. Each database gets its own set of files on the file system. A single MongoDB server typically has multiple databases.
- Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A collection exists within a single database. Collections do not enforce a schema. Documents within a collection can have different fields. Typically, all documents in a collection are of similar or related purpose.
- A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection's documents may hold different types of data
- Example document/JSON:
- {
- _id: ObjectId(7df78ad8902c)
- title: 'MongoDB Overview',
- description: 'MongoDB is no sql database',
- by: 'tutorials point',
- url: 'http://www.tutorialspoint.com',
- tags: ['mongodb', 'database', 'NoSQL'],
- likes: 100,
- comments: [
- {
- user:'user1',
- message: 'My first comment',
- dateCreated: new Date(2011,1,20,2,15),
- like: 0
- },
- {
- user:'user2',
- message: 'My second comments',
- dateCreated: new Date(2011,1,25,7,45),
- like: 5
- }
- ]
- }
- _id is a 12 bytes hexadecimal number which assures the uniqueness of every document. You can provide _id while inserting the document. If you don’t provide then MongoDB provides a unique id for every document. These 12 bytes first 4 bytes for the current timestamp, next 3 bytes for machine id, next 2 bytes for process id of MongoDB server and remaining 3 bytes are simple incremental VALUE.
- Advantages of MongoDB:
- Schema less − MongoDB is a document database in which one collection holds different documents. Number of fields, content and size of the document can differ from one document to another
- Structure of a single object is clear
- No complex joins
- Deep query-ability. MongoDB supports dynamic queries on documents using a document-based query language that's nearly as powerful as SQL
- Tuning
- Ease of scale-out − MongoDB is easy to scale.
- Conversion/mapping of application objects to database objects not needed
- Uses internal memory for storing the (windowed) working set, enabling faster access of data.
- Index on any attribute
- Replication and high availability
- Auto-sharding
- Sharding is a type of database partitioning that separates very large databases the into smaller, faster, more easily managed parts called data shards. The word shard means a small part of a whole.
- Sharding in MongoDB is the process of storing data records across multiple machines and it is MongoDB's approach to meeting the demands of data growth. As the size of the data increases, a single machine may not be sufficient to store the data nor provide an acceptable read and write throughput
- Rich queries
- Fast in-place updates
- Professional support by MongoDB
- MongoDB should be used where there is:
- Big Data
- Content Mgmt and Delivery
- Mobile and Social Infrastructure
- User Data Management
- Data hub
- Installation and MongoDB service:
- Assuming mongo is installed at path: D:\setup\mongodb
- Go to bin dir inside.
- As instructed in above part of the blog, you need to create data/db and log directories inside and then start mongo.
- D:\setup\mongodb\bin>mongod.exe --dbpath "d:\setup\mongodb\data"
- This will show waiting for connections message on the console output, which indicates that the mongod.exe process is running successfully.Now to run the MongoDB, you need to open another command prompt and issue the following command.
- D:\set up\mongodb\bin>mongo.exeMongoDB shell version: 2.4.6connecting to: test>db.test.save( { a: 1 } )>db.test.find(){ "_id" : ObjectId(5879b0f65a56a454), "a" : 1 }>
- This will show that MongoDB is installed and run successfully. Next time when you run MongoDB, you need to issue only commands.
- D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"D:\set up\mongodb\bin>mongo.exe
- Start / Stop/ Restart MongoDB on linux:
- sudo service mongodb startsudo service mongodb stopsudo service mongodb
- To get a list of commands, type db.help() in MongoDB client. This will give you a list of commands
- To get stats about MongoDB server, type the command db.stats() in MongoDB client. This will show the database name, number of collection and documents in the database
- Example of how simple Mongo can, compared to RDBMS:
- Suppose a client needs a database design for his blog/website and see the differences between RDBMS and MongoDB schema design. Website has the following requirements.
- Every post has the unique title, description and url.
- Every post can have one or more tags.
- Every post has the name of its publisher and total number of likes.
- Every post has comments given by users along with their name, message, data-time and likes.
- On each post, there can be zero or more comments.
In RDBMS schema, design for above requirements will have minimum three tables. -
- While in MongoDB schema, design will have one collection post and the following structure −{_id: POST_IDtitle: TITLE_OF_POST,description: POST_DESCRIPTION,by: POST_BY,url: URL_OF_POST,tags: [TAG1, TAG2, TAG3],likes: TOTAL_LIKES,comments: [{user:'COMMENT_BY',message: TEXT,dateCreated: DATE_TIME,like: LIKES},{user:'COMMENT_BY',message: TEXT,dateCreated: DATE_TIME,like: LIKES}]}
- So while showing the data, in RDBMS you need to join three tables and in MongoDB, data will be shown from one collection only.
- MongoDB db.dropDatabase() command is used to drop a existing database.
>db.dropDatabase()
This will delete the selected database. If you have not selected any database, then it will delete default 'test' database.
Example
First, check the list of available databases by using the command, show dbs.
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
If you want to delete new database <mydb>, then dropDatabase() command would be as follows −
>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
Now check list of databases.
>show dbs
local 0.78125GB
test 0.23012GB - The createCollection() Method
MongoDB db.createCollection(name, options) is used to create collection.
>db.createCollection(name, options)
In the command, name is name of collection to be created. Options is a document and is used to specify configuration of collection. - While inserting the document, MongoDB first checks size field of capped collection, then it checks max field.
- Example:>use testswitched to db test>db.createCollection("mycollection"){ "ok" : 1 }>You can check the created collection by using the command show collections.>show collectionsmycollectionsystem.indexesThe following example shows the syntax of createCollection() method with few important options −>db.createCollection("mycol", { capped : true, autoIndexId : true, size :6142800, max : 10000 } ){ "ok" : 1 }>In MongoDB, you don't need to create collection. MongoDB creates collection automatically, when you insert some document.>db.tutorialspoint.insert({"name" : "tutorialspoint"})>show collectionsmycolmycollectionsystem.indexestutorialspoint
- MongoDB's db.collection.drop() is used to drop a collection from the database
- Syntax: db.COLLECTION_NAME.drop()
>db.mycollection.drop()true>- drop() method will return true, if the selected collection is dropped successfully, otherwise it will return false.
- Datatypes:
- MongoDB supports many datatypes. Some of them are −
- String − This is the most commonly used datatype to store the data. String in MongoDB must be UTF-8 valid.
- Integer − This type is used to store a numerical value. Integer can be 32 bit or 64 bit depending upon your server.
- Boolean − This type is used to store a boolean (true/ false) value.
- Double − This type is used to store floating point 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 arrays or list or multiple values into one key.
- Timestamp − ctimestamp. This can be handy for recording when a document has been modified or added.
- 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. You can specify your own date time by creating object of Date and passing day, month, year into it.
- Object ID − This datatype is used to store the document’s ID.
- Binary data − This datatype is used to store binary data.
- Code − This datatype is used to store JavaScript code into the document.
- Regular expression − This datatype is used to store regular expression.
- insert() Method
- To insert data into MongoDB collection, you need to use MongoDB's insert() or save()method
- Syntax: >db.COLLECTION_NAME.insert(document)
- >db.mycol.insert({
- _id: ObjectId(7df78ad8902c),
- title: 'MongoDB Overview',
- description: 'MongoDB is no sql database',
- by: 'tutorials point',
- url: 'http://www.tutorialspoint.com',
- tags: ['mongodb', 'database', 'NoSQL'],
- likes: 100
- })
- Here mycol is our collection name, as created in the previous chapter. If the collection doesn't exist in the database, then MongoDB will create this collection and then insert a document into it.
- In the inserted document, if we don't specify the _id parameter, then MongoDB assigns a unique ObjectId for this document.
- To insert multiple documents in a single query, you can pass an array of documents in insert() command
- >db.post.insert([
- {
- title: 'MongoDB Overview',
- description: 'MongoDB is no sql database',
- by: 'tutorials point',
- url: 'http://www.tutorialspoint.com',
- tags: ['mongodb', 'database', 'NoSQL'],
- likes: 100
- },
- {
- title: 'NoSQL Database',
- description: "NoSQL database doesn't have tables",
- by: 'tutorials point',
- url: 'http://www.tutorialspoint.com',
- tags: ['mongodb', 'database', 'NoSQL'],
- likes: 20,
- comments: [
- {
- user:'user1',
- message: 'My first comment',
- dateCreated: new Date(2013,11,10,2,35),
- like: 0
- }
- ]
- }
- ])
- To insert the document you can use db.post.save(document) also. If you don't specify _id in the document then save() method will work same as insert() method. If you specify _id then it will replace whole data of document containing _id as specified in save() method
RDBMS Where Clause Equivalents in MongoDB
To query the document on the basis of some condition, you can use following operations.
Operation Syntax Example RDBMS Equivalent Equality {<key>:<value>} db.mycol.find({"by":"tutorials point"}).pretty() where by = 'tutorials point' Less Than {<key>:{$lt:<value>}} db.mycol.find({"likes":{$lt:50}}).pretty() where likes < 50 Less Than Equals {<key>:{$lte:<value>}} db.mycol.find({"likes":{$lte:50}}).pretty() where likes <= 50 Greater Than {<key>:{$gt:<value>}} db.mycol.find({"likes":{$gt:50}}).pretty() where likes > 50 Greater Than Equals {<key>:{$gte:<value>}} db.mycol.find({"likes":{$gte:50}}).pretty() where likes >= 50 Not Equals {<key>:{$ne:<value>}} db.mycol.find({"likes":{$ne:50}}).pretty() where likes != 50 - In the find() method, if you pass multiple keys by separating them by ',' then MongoDB treats it as AND condition. Following is the basic syntax of AND −
- >db.mycol.find(
- {
- $and: [
- {key1: value1}, {key2:value2}
- ]
- }
- ).pretty()
- Exanple:
- Following example will show all the tutorials written by 'tutorials point' and whose title is 'MongoDB Overview'.
- >db.mycol.find({$and:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty()
- {
- "_id": ObjectId(7df78ad8902c),
- "title": "MongoDB Overview",
- "description": "MongoDB is no sql database",
- "by": "tutorials point",
- "url": "http://www.tutorialspoint.com",
- "tags": ["mongodb", "database", "NoSQL"],
- "likes": "100"
- }
- OR Example:
- >db.mycol.find({$or:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty()
- {
- "_id": ObjectId(7df78ad8902c),
- "title": "MongoDB Overview",
- "description": "MongoDB is no sql database",
- "by": "tutorials point",
- "url": "http://www.tutorialspoint.com",
- "tags": ["mongodb", "database", "NoSQL"],
- "likes": "100"
- }
- AND , OR together:
- show the documents that have likes greater than 10 and whose title is either 'MongoDB Overview' or by is 'tutorials point'. Equivalent SQL where clause is 'where likes>10 AND (by = 'tutorials point' OR title = 'MongoDB Overview')'
- >db.mycol.find({"likes": {$gt:10}, $or: [{"by": "tutorials point"},
- {"title": "MongoDB Overview"}]}).pretty()
- {
- "_id": ObjectId(7df78ad8902c),
- "title": "MongoDB Overview",
- "description": "MongoDB is no sql database",
- "by": "tutorials point",
- "url": "http://www.tutorialspoint.com",
- "tags": ["mongodb", "database", "NoSQL"],
- "likes": "100"
- }
- MongoDB's update() and save() methods are used to update document into a collection. The update() method updates the values in the existing document while the save() method replaces the existing document with the document passed in save() method
- The basic syntax of update() method is as follows −
- >db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
- Consider the mycol collection has the following data.
- { "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
- { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
- { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
- Following example will set the new title 'New MongoDB Tutorial' of the documents whose title is 'MongoDB Overview'.
- >db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})
- >db.mycol.find()
- { "_id" : ObjectId(5983548781331adf45ec5), "title":"New MongoDB Tutorial"}
- { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
- { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
- >
- By default, MongoDB will update only a single document. To update multiple documents, you need to set a parameter 'multi' to true.
- >db.mycol.update({'title':'MongoDB Overview'},
- {$set:{'title':'New MongoDB Tutorial'}},{multi:true})
- The save() method replaces the existing document with the new document passed in the save() method.
- The basic syntax of MongoDB save() method is shown below −
- >db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
- Following example will replace the document with the _id '5983548781331adf45ec5'.
- >db.mycol.save(
- {
- "_id" : ObjectId(5983548781331adf45ec5), "title":"Tutorials Point New Topic",
- "by":"Tutorials Point"
- }
- )
- >db.mycol.find()
- { "_id" : ObjectId(5983548781331adf45ec5), "title":"Tutorials Point New Topic",
- "by":"Tutorials Point"}
- { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
- { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
- >
- MongoDB's remove() method is used to remove a document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag.
- deletion criteria − (Optional) deletion criteria according to documents will be removed.
- justOne − (Optional) if set to true or 1, then remove only one document.
- >db.mycol.remove({'title':'MongoDB Overview'})
- >db.mycol.find()
- { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
- { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
- >
- If there are multiple records and you want to delete only the first record, then set justOne parameter in remove() method.
- >db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)
- If you don't specify deletion criteria, then MongoDB will delete whole documents from the collection. This is equivalent of SQL's truncate command.
- >db.mycol.remove({})
- >db.mycol.find()
- >
- MongoDB's find() method, explained in MongoDB Query Document accepts second optional parameter that is list of fields that you want to retrieve. In MongoDB, when you execute find() method, then it displays all fields of a document. To limit this, you need to set a list of fields with value 1 or 0. 1 is used to show the field while 0 is used to hide the fields.
- The basic syntax of find() method with projection is as follows −
- >db.COLLECTION_NAME.find({},{KEY:1})
- Consider the collection mycol has the following data −
- { "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
- { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
- { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
- Following example will display the title of the document while querying the document.
- >db.mycol.find({},{"title":1,_id:0})
- {"title":"MongoDB Overview"}
- {"title":"NoSQL Overview"}
- {"title":"Tutorials Point Overview"}
- >
- Please note _id field is always displayed while executing find() method, if you don't want this field, then you need to set it as 0.


