Author: alien

  • Khóa học miễn phí MongoDB – Update Document nhận dự án làm có lương

    MongoDB – Update Document



    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.

    MongoDB Update() Method

    The update() method updates the values in the existing document.

    Syntax

    The basic syntax of update() method is as follows −

    >db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
    

    Example

    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''}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    >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})
    

    MongoDB Save() Method

    The save() method replaces the existing document with the new document passed in the save() method.

    Syntax

    The basic syntax of MongoDB save() method is shown below −

    >db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
    

    Example

    Following example will replace the document with the _id ”5983548781331adf45ec5”.

    >db.mycol.save(
       {
          "_id" : ObjectId("507f191e810c19729de860ea"),
    		"title":"Tutorials Point New Topic",
          "by":"Tutorials Point"
       }
    )
    WriteResult({
    	"nMatched" : 0,
    	"nUpserted" : 1,
    	"nModified" : 0,
    	"_id" : ObjectId("507f191e810c19729de860ea")
    })
    >db.mycol.find()
    { "_id" : ObjectId("507f191e810c19729de860e6"), "title":"Tutorials Point New Topic",
       "by":"Tutorials Point"}
    { "_id" : ObjectId("507f191e810c19729de860e6"), "title":"NoSQL Overview"}
    { "_id" : ObjectId("507f191e810c19729de860e6"), "title":"Tutorials Point Overview"}
    >
    

    MongoDB findOneAndUpdate() method

    The findOneAndUpdate() method updates the values in the existing document.

    Syntax

    The basic syntax of findOneAndUpdate() method is as follows −

    >db.COLLECTION_NAME.findOneAndUpdate(SELECTIOIN_CRITERIA, UPDATED_DATA)
    

    Example

    Assume we have created a collection named empDetails and inserted three documents in it as shown below −

    > db.empDetails.insertMany(
    	[
    		{
    			First_Name: "Radhika",
    			Last_Name: "Sharma",
    			Age: "26",
    			e_mail: "radhika_sharma.123@gmail.com",
    			phone: "9000012345"
    		},
    		{
    			First_Name: "Rachel",
    			Last_Name: "Christopher",
    			Age: "27",
    			e_mail: "Rachel_Christopher.123@gmail.com",
    			phone: "9000054321"
    		},
    		{
    			First_Name: "Fathima",
    			Last_Name: "Sheik",
    			Age: "24",
    			e_mail: "Fathima_Sheik.123@gmail.com",
    			phone: "9000054321"
    		}
    	]
    )
    

    Following example updates the age and email values of the document with name ”Radhika”.

    > db.empDetails.findOneAndUpdate(
    	{First_Name: ''Radhika''},
    	{ $set: { Age: ''30'',e_mail: ''radhika_newemail@gmail.com''}}
    )
    {
    	"_id" : ObjectId("5dd6636870fb13eec3963bf5"),
    	"First_Name" : "Radhika",
    	"Last_Name" : "Sharma",
    	"Age" : "30",
    	"e_mail" : "radhika_newemail@gmail.com",
    	"phone" : "9000012345"
    }
    

    MongoDB updateOne() method

    This methods updates a single document which matches the given filter.

    Syntax

    The basic syntax of updateOne() method is as follows −

    >db.COLLECTION_NAME.updateOne(<filter>, <update>)
    

    Example

    > db.empDetails.updateOne(
    	{First_Name: ''Radhika''},
    	{ $set: { Age: ''30'',e_mail: ''radhika_newemail@gmail.com''}}
    )
    { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 0 }
    >
    

    MongoDB updateMany() method

    The updateMany() method updates all the documents that matches the given filter.

    Syntax

    The basic syntax of updateMany() method is as follows −

    >db.COLLECTION_NAME.update(<filter>, <update>)
    

    Example

    > db.empDetails.updateMany(
    	{Age:{ $gt: "25" }},
    	{ $set: { Age: ''00''}}
    )
    { "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
    

    You can see the updated values if you retrieve the contents of the document using the find method as shown below −

    > db.empDetails.find()
    { "_id" : ObjectId("5dd6636870fb13eec3963bf5"), "First_Name" : "Radhika", "Last_Name" : "Sharma", "Age" : "00", "e_mail" : "radhika_newemail@gmail.com", "phone" : "9000012345" }
    { "_id" : ObjectId("5dd6636870fb13eec3963bf6"), "First_Name" : "Rachel", "Last_Name" : "Christopher", "Age" : "00", "e_mail" : "Rachel_Christopher.123@gmail.com", "phone" : "9000054321" }
    { "_id" : ObjectId("5dd6636870fb13eec3963bf7"), "First_Name" : "Fathima", "Last_Name" : "Sheik", "Age" : "24", "e_mail" : "Fathima_Sheik.123@gmail.com", "phone" : "9000054321" }
    >
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MongoDB – Insert Document nhận dự án làm có lương

    MongoDB – Insert Document



    In this chapter, we will learn how to insert document in MongoDB collection.

    The insert() Method

    To insert data into MongoDB collection, you need to use MongoDB”s insert() or save() method.

    Syntax

    The basic syntax of insert() command is as follows −

    >db.COLLECTION_NAME.insert(document)
    

    Example

    > db.users.insert({
    ... _id : ObjectId("507f191e810c19729de860ea"),
    ... title: "MongoDB Overview",
    ... description: "MongoDB is no sql database",
    ... by: "tutorials point",
    ... url: "http://www.tutorialspoint.com",
    ... tags: [''mongodb'', ''database'', ''NoSQL''],
    ... likes: 100
    ... })
    WriteResult({ "nInserted" : 1 })
    >
    

    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.

    _id is 12 bytes hexadecimal number unique for every document in a collection. 12 bytes are divided as follows −

    _id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)
    

    You can also pass an array of documents into the insert() method as shown below:.

    > db.createCollection("post")
    > 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
    		}
    	]
    }
    ])
    BulkWriteResult({
    	"writeErrors" : [ ],
    	"writeConcernErrors" : [ ],
    	"nInserted" : 2,
    	"nUpserted" : 0,
    	"nMatched" : 0,
    	"nModified" : 0,
    	"nRemoved" : 0,
    	"upserted" : [ ]
    })
    >
    

    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.

    The insertOne() method

    If you need to insert only one document into a collection you can use this method.

    Syntax

    The basic syntax of insert() command is as follows −

    >db.COLLECTION_NAME.insertOne(document)
    

    Example

    Following example creates a new collection named empDetails and inserts a document using the insertOne() method.

    > db.createCollection("empDetails")
    { "ok" : 1 }
    

    > db.empDetails.insertOne(
    	{
    		First_Name: "Radhika",
    		Last_Name: "Sharma",
    		Date_Of_Birth: "1995-09-26",
    		e_mail: "radhika_sharma.123@gmail.com",
    		phone: "9848022338"
    	})
    {
    	"acknowledged" : true,
    	"insertedId" : ObjectId("5dd62b4070fb13eec3963bea")
    }
    >
    

    The insertMany() method

    You can insert multiple documents using the insertMany() method. To this method you need to pass an array of documents.

    Example

    Following example inserts three different documents into the empDetails collection using the insertMany() method.

    > db.empDetails.insertMany(
    	[
    		{
    			First_Name: "Radhika",
    			Last_Name: "Sharma",
    			Date_Of_Birth: "1995-09-26",
    			e_mail: "radhika_sharma.123@gmail.com",
    			phone: "9000012345"
    		},
    		{
    			First_Name: "Rachel",
    			Last_Name: "Christopher",
    			Date_Of_Birth: "1990-02-16",
    			e_mail: "Rachel_Christopher.123@gmail.com",
    			phone: "9000054321"
    		},
    		{
    			First_Name: "Fathima",
    			Last_Name: "Sheik",
    			Date_Of_Birth: "1990-02-16",
    			e_mail: "Fathima_Sheik.123@gmail.com",
    			phone: "9000054321"
    		}
    	]
    )
    {
    	"acknowledged" : true,
    	"insertedIds" : [
    		ObjectId("5dd631f270fb13eec3963bed"),
    		ObjectId("5dd631f270fb13eec3963bee"),
    		ObjectId("5dd631f270fb13eec3963bef")
    	]
    }
    >
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MongoDB – Create Collection nhận dự án làm có lương

    MongoDB – Create Collection



    In this chapter, we will see how to create a collection using MongoDB.

    The createCollection() Method

    MongoDB db.createCollection(name, options) is used to create collection.

    Syntax

    Basic syntax of createCollection() command is as follows −

    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.

    Parameter Type Description
    Name String Name of the collection to be created
    Options Document (Optional) Specify options about memory size and indexing

    Options parameter is optional, so you need to specify only the name of the collection. Following is the list of options you can use −

    Field Type Description
    capped Boolean (Optional) If true, enables a capped collection. Capped collection is a fixed size collection that automatically overwrites its oldest entries when it reaches its maximum size. If you specify true, you need to specify size parameter also.
    autoIndexId Boolean (Optional) If true, automatically create index on _id field.s Default value is false.
    size number (Optional) Specifies a maximum size in bytes for a capped collection. If capped is true, then you need to specify this field also.
    max number (Optional) Specifies the maximum number of documents allowed in the capped collection.

    While inserting the document, MongoDB first checks size field of capped collection, then it checks max field.

    Examples

    Basic syntax of createCollection() method without options is as follows −

    >use test
    switched to db test
    >db.createCollection("mycollection")
    { "ok" : 1 }
    >
    

    You can check the created collection by using the command show collections.

    >show collections
    mycollection
    system.indexes
    

    The following example shows the syntax of createCollection() method with few important options −

    > db.createCollection("mycol", { capped : true, autoIndexID : true, size : 6142800, max : 10000 } ){
    "ok" : 0,
    "errmsg" : "BSON field ''create.autoIndexID'' is an unknown field.",
    "code" : 40415,
    "codeName" : "Location40415"
    }
    >
    

    In MongoDB, you don”t need to create collection. MongoDB creates collection automatically, when you insert some document.

    >db.tutorialspoint.insert({"name" : "tutorialspoint"}),
    WriteResult({ "nInserted" : 1 })
    >show collections
    mycol
    mycollection
    system.indexes
    tutorialspoint
    >
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MongoDB – Drop Database nhận dự án làm có lương

    MongoDB – Drop Database



    In this chapter, we will see how to drop a database using MongoDB command.

    The dropDatabase() Method

    MongoDB db.dropDatabase() command is used to drop a existing database.

    Syntax

    Basic syntax of dropDatabase() command is as follows −

    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
    >
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MongoDB – Advantages nhận dự án làm có lương

    MongoDB – Advantages



    Any relational database has a typical schema design that shows number of tables and the relationship between these tables. While in MongoDB, there is no concept of relationship.

    Advantages of MongoDB over RDBMS

    • 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.

    Why Use MongoDB?

    • Document Oriented Storage − Data is stored in the form of JSON style documents.

    • Index on any attribute

    • Replication and high availability

    • Auto-Sharding

    • Rich queries

    • Fast in-place updates

    • Professional support by MongoDB

    Where to Use MongoDB?

    • Big Data

    • Content Management and Delivery

    • Mobile and Social Infrastructure

    • User Data Management

    • Data Hub


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MongoDB – Data Types nhận dự án làm có lương

    MongoDB – 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.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MongoDB – Home nhận dự án làm có lương

    MongoDB Tutorial

    MongoDB Tutorial

    Table of content






    MongoDB Tutorial

    The MongoDB is an open-source document database and leading NoSQL database. MongoDB is written in C++. This tutorial will give you great understanding on MongoDB concepts needed to create and deploy a highly scalable and performance-oriented database.

    MongoDB features are flexible data models that allows the storage of unstructured data. This provides full support indexing, replication, capabilities and also user friendly APIs.

    The MongoDB is a multipurpose dataset that is used for modern application development and cloud environments. This scalable architecture enables us to handle system demands and also adding more nodes to distribute the load.

    MongoDB is an open source NOSQL dataset in C++, this offers flexible data models, indexing, replication and modern applications for scalable architecture.

    MongoDB Basic Commands

    We have a list of standard MongoDb commands to interact with the database, These commands are CREATE, READ, INSERT, UPDATE, DELETE, DROP and AGGREGATE can be classified into following groups based on their nature −

    Command Description
    CREATE Creates a new table in the database and other objects in the database.
    INSERT Inserts collection name in existing database.
    DROP Deletes an entire table or specified objects in the database.
    UPDATE Updates the document into a collection.

    Why to Learn MongoDB?

    MongoDB can handle unstructured data, which provides better indexing and operations. MongoDB ensures the development software applications that can handle all sorts of data in a scalable way.

    MongoDB is a rapid iterative development that enables the collaboration of a large number of teams. MongoDB has become the most necessary database in the world, which makes it easy for every developer to store, manage, and retrieve data.

    MongoDB Applications

    MongoDB is a NoSQL database. MongoDB provides following functionality to the database programmers −

    • Stores user data, comments and metadata

    • MongoDB performs complex analytics queries and stores the behavioral data.

    • This is used to manage chain data and optimize logistics.

    • Environmental data and IoT devices are stored and analyzed.

    Who Should Learn MongoDB

    This MongoDB tutorial will help web developers, devops engineer, mobile apps, backend, full-stack, database administrators, etc. We recommend reading this tutorial, in the sequence listed in the left side menu.

    Prerequisites to Learn MongoDB

    Before proceeding with this tutorial, you should have a basic understanding of database, text editor and execution of programs, etc. Because we are going to develop high performance database, so it will be good if you have an understanding on the basic concepts of Database (RDBMS).

    MongoDB is typically used in the development of applications, at least one programming language is very helpful to work with APIs.

    MongoDB Jobs and Opportunities

    MongoDB is in high demand professionally and it is exponentially growing in the IT industry.

    In MongoDB jobs are in high demand with a growth rate of 50%. The NoSQL database market is growing at a rate of 30%.

    Average salaries for a MongoDB professional are around $100,000 to $200,000. This may vary depending on the location. The Following companies recruit MongoDB professionals:

    • Accenture
    • IBM
    • Deloitte
    • Capgemini
    • TCS
    • Infosys
    • Wipro
    • Google
    • Amazon
    • Microsoft
    • HCL

    You could be the next employee for any of these major companies. We have developed great learning material for MongoDB that helps you prepare for technical interviews and certifications. So, start learning MongoDB using our tutorial anywhere and anytime, absolutely at your place.

    Frequently Asked Questions about MongoDB

    There are some very Frequently Asked Questions(FAQ) about MongoDB, this section tries to answer them briefly.

    MangoDB can manage document information, stores and retrieves the information. This is used for high data storage and performing large amount of data while performing the dataset. This is a distributed database at its level, high availability, horizontal scaling are built in and easy to use.

    Sharding is a database that separates large database into smaller, faster, and easily managed parts. These smaller parts are called data shards. Shard is defined as a “small part of a whole”.

    MongoDB is not a programming language, but this is a NOSQL database. This query language allows us to interact with the data. MongoDB is a non-relational database management system that stores the data in flexible JSON documents.

    This supports multi-document transactions, even though they are less performed as compared to traditional relational databases.

    This can be used in memory intensive situation because memory maps the entire data file into memory.

    This is designed for eventual consistency, which means there can be a lag before all the nodes in a distributed system.

    Yes, you can learn MongoDB without knowledge of SQL. MongoDB uses its own query language, which is different from SQL. You need to learn about NoSQL databases, and these vary very much from the SQL database. MongoDB Compass is a user-friendly interface that visualizes your data and understands your schema without using the command line.

    MongoDB supports wide range of platforms, that are useful for developing various environments.

    Operating System performs Windows 7 and Linux with various distributions.

    Cloud Platform in MongoDB manages data-base-as-a-service available in Google, AWS and Azure.

    Docker provides the official Docker images for deployment.

    Following are MongoDB Indexes.

    • Single Field Index.
    • Compound Index.
    • Multikey Index.
    • Text Index.
    • Hashed Index.

    MongoDB implements the primary key using the ”_id” field. Every primary key acts as a different identifier for the document. This field is automatically created by MongoDB when the document is inserted. This can be any type, as long as it is different from the collection.

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MongoDB – Overview nhận dự án làm có lương

    MongoDB – Overview



    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

    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

    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.

    Document

    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.

    The following table shows the relationship of RDBMS terminology with 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)
    Database Server and Client
    mysqld/Oracle mongod
    mysql/sqlplus mongo

    Sample Document

    Following example shows the document structure of a blog site, which is simply a comma separated key value pair.

    {
       _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.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MongoDB – Environment nhận dự án làm có lương

    MongoDB – Environment



    Let us now see how to install MongoDB on Windows.

    Install MongoDB On Windows

    To install MongoDB on Windows, first download the latest release of MongoDB from .

    Mongodb Cloud

    Enter the required details, select the Server tab, in it you can choose the version of MongoDB, operating system and, packaging as:

    Mongodb Community

    Now install the downloaded file, by default, it will be installed in the folder C:Program Files.

    MongoDB requires a data folder to store its files. The default location for the MongoDB data directory is c:datadb. So you need to create this folder using the Command Prompt. Execute the following command sequence.

    C:>md data
    C:md datadb
    

    Then you need to specify set the dbpath to the created directory in mongod.exe. For the same, issue the following commands.

    In the command prompt, navigate to the bin directory current in the MongoDB installation folder. Suppose my installation folder is C:Program FilesMongoDB

    C:UsersXYZ>d:cd C:Program FilesMongoDBServer4.2bin
    C:Program FilesMongoDBServer4.2bin>mongod.exe --dbpath "C: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.

    C:Program FilesMongoDBServer4.2bin>mongo.exe
    MongoDB shell version v4.2.1
    connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
    Implicit session: session { "id" : UUID("4260beda-f662-4cbe-9bc7-5c1f2242663c") }
    MongoDB server version: 4.2.1
    >
    

    This will show that MongoDB is installed and run successfully. Next time when you run MongoDB, you need to issue only commands.

    C:Program FilesMongoDBServer4.2bin>mongod.exe --dbpath "C:data"
    C:Program FilesMongoDBServer4.2bin>mongo.exe
    

    Install MongoDB on Ubuntu

    Run the following command to import the MongoDB public GPG key −

    sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
    

    Create a /etc/apt/sources.list.d/mongodb.list file using the following command.

    echo ''deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen''
       | sudo tee /etc/apt/sources.list.d/mongodb.list
    

    Now issue the following command to update the repository −

    sudo apt-get update
    

    Next install the MongoDB by using the following command −

    apt-get install mongodb-10gen = 4.2
    

    In the above installation, 2.2.3 is currently released MongoDB version. Make sure to install the latest version always. Now MongoDB is installed successfully.

    Start MongoDB

    sudo service mongodb start
    

    Stop MongoDB

    sudo service mongodb stop
    

    Restart MongoDB

    sudo service mongodb restart
    

    To use MongoDB run the following command.

    mongo
    

    This will connect you to running MongoDB instance.

    MongoDB Help

    To get a list of commands, type db.help() in MongoDB client. This will give you a list of commands as shown in the following screenshot.

    DB Help

    MongoDB Statistics

    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. Output of the command is shown in the following screenshot.

    DB Stats

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MongoDB – Data Modeling nhận dự án làm có lương

    MongoDB – Data Modelling



    Data in MongoDB has a flexible schema.documents in the same collection. They do not need to have the same set of fields or structure Common fields in a collection’s documents may hold different types of data.

    Data Model Design

    MongoDB provides two types of data models: — Embedded data model and Normalized data model. Based on the requirement, you can use either of the models while preparing your document.

    Embedded Data Model

    In this model, you can have (embed) all the related data in a single document, it is also known as de-normalized data model.

    For example, assume we are getting the details of employees in three different documents namely, Personal_details, Contact and, Address, you can embed all the three documents in a single one as shown below −

    {
    	_id: ,
    	Emp_ID: "10025AE336"
    	Personal_details:{
    		First_Name: "Radhika",
    		Last_Name: "Sharma",
    		Date_Of_Birth: "1995-09-26"
    	},
    	Contact: {
    		e-mail: "radhika_sharma.123@gmail.com",
    		phone: "9848022338"
    	},
    	Address: {
    		city: "Hyderabad",
    		Area: "Madapur",
    		State: "Telangana"
    	}
    }
    

    Normalized Data Model

    In this model, you can refer the sub documents in the original document, using references. For example, you can re-write the above document in the normalized model as:

    Employee:

    {
    	_id: <ObjectId101>,
    	Emp_ID: "10025AE336"
    }
    

    Personal_details:

    {
    	_id: <ObjectId102>,
    	empDocID: " ObjectId101",
    	First_Name: "Radhika",
    	Last_Name: "Sharma",
    	Date_Of_Birth: "1995-09-26"
    }
    

    Contact:

    {
    	_id: <ObjectId103>,
    	empDocID: " ObjectId101",
    	e-mail: "radhika_sharma.123@gmail.com",
    	phone: "9848022338"
    }
    

    Address:

    {
    	_id: <ObjectId104>,
    	empDocID: " ObjectId101",
    	city: "Hyderabad",
    	Area: "Madapur",
    	State: "Telangana"
    }
    

    Considerations while designing Schema in MongoDB

    • Design your schema according to user requirements.

    • Combine objects into one document if you will use them together. Otherwise separate them (but make sure there should not be need of joins).

    • Duplicate the data (but limited) because disk space is cheap as compare to compute time.

    • Do joins while write, not on read.

    • Optimize your schema for most frequent use cases.

    • Do complex aggregation in the schema.

    Example

    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.

    RDBMS Schema Design

    While in MongoDB schema, design will have one collection post and the following structure −

    {
       _id: POST_ID
       title: 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.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc