Author: alien

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

    MongoDB – Deployment



    When you are preparing a MongoDB deployment, you should try to understand how your application is going to hold up in production. It’s a good idea to develop a consistent, repeatable approach to managing your deployment environment so that you can minimize any surprises once you’re in production.

    The best approach incorporates prototyping your set up, conducting load testing, monitoring key metrics, and using that information to scale your set up. The key part of the approach is to proactively monitor your entire system – this will help you understand how your production system will hold up before deploying, and determine where you will need to add capacity. Having insight into potential spikes in your memory usage, for example, could help put out a write-lock fire before it starts.

    To monitor your deployment, MongoDB provides some of the following commands −

    mongostat

    This command checks the status of all running mongod instances and return counters of database operations. These counters include inserts, queries, updates, deletes, and cursors. Command also shows when you’re hitting page faults, and showcase your lock percentage. This means that you”re running low on memory, hitting write capacity or have some performance issue.

    To run the command, start your mongod instance. In another command prompt, go to bin directory of your mongodb installation and type mongostat.

    D:set upmongodbbin>mongostat
    

    Following is the output of the command −

    mongostat mongostat2

    mongotop

    This command tracks and reports the read and write activity of MongoDB instance on a collection basis. By default, mongotop returns information in each second, which you can change it accordingly. You should check that this read and write activity matches your application intention, and you’re not firing too many writes to the database at a time, reading too frequently from a disk, or are exceeding your working set size.

    To run the command, start your mongod instance. In another command prompt, go to bin directory of your mongodb installation and type mongotop.

    D:set upmongodbbin>mongotop
    

    Following is the output of the command −

    mongotop mongotop2

    To change mongotop command to return information less frequently, specify a specific number after the mongotop command.

    D:set upmongodbbin>mongotop 30
    

    The above example will return values every 30 seconds.

    Apart from the MongoDB tools, 10gen provides a free, hosted monitoring service, MongoDB Management Service (MMS), that provides a dashboard and gives you a view of the metrics from your entire cluster.


    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 – Sharding nhận dự án làm có lương

    MongoDB – Sharding



    Sharding 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. Sharding solves the problem with horizontal scaling. With sharding, you add more machines to support data growth and the demands of read and write operations.

    Why Sharding?

    • In replication, all writes go to master node

    • Latency sensitive queries still go to master

    • Single replica set has limitation of 12 nodes

    • Memory can”t be large enough when active dataset is big

    • Local disk is not big enough

    • Vertical scaling is too expensive

    Sharding in MongoDB

    The following diagram shows the Sharding in MongoDB using sharded cluster.

    MongoDB Sharding

    In the following diagram, there are three main components −

    • Shards − Shards are used to store data. They provide high availability and data consistency. In production environment, each shard is a separate replica set.

    • Config Servers − Config servers store the cluster”s metadata. This data contains a mapping of the cluster”s data set to the shards. The query router uses this metadata to target operations to specific shards. In production environment, sharded clusters have exactly 3 config servers.

    • Query Routers − Query routers are basically mongo instances, interface with client applications and direct operations to the appropriate shard. The query router processes and targets the operations to shards and then returns results to the clients. A sharded cluster can contain more than one query router to divide the client request load. A client sends requests to one query router. Generally, a sharded cluster have many query routers.


    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 – Indexing nhận dự án làm có lương

    MongoDB – Indexing



    Indexes support the efficient resolution of queries. Without indexes, MongoDB must scan every document of a collection to select those documents that match the query statement. This scan is highly inefficient and require MongoDB to process a large volume of data.

    Indexes are special data structures, that store a small portion of the data set in an easy-to-traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field as specified in the index.

    The createIndex() Method

    To create an index, you need to use createIndex() method of MongoDB.

    Syntax

    The basic syntax of createIndex() method is as follows().

    >db.COLLECTION_NAME.createIndex({KEY:1})
    

    Here key is the name of the field on which you want to create index and 1 is for ascending order. To create index in descending order you need to use -1.

    Example

    >db.mycol.createIndex({"title":1})
    {
    	"createdCollectionAutomatically" : false,
    	"numIndexesBefore" : 1,
    	"numIndexesAfter" : 2,
    	"ok" : 1
    }
    >
    

    In createIndex() method you can pass multiple fields, to create index on multiple fields.

    >db.mycol.createIndex({"title":1,"description":-1})
    >
    

    This method also accepts list of options (which are optional). Following is the list −

    Parameter Type Description
    background Boolean Builds the index in the background so that building an index does not block other database activities. Specify true to build in the background. The default value is false.
    unique Boolean Creates a unique index so that the collection will not accept insertion of documents where the index key or keys match an existing value in the index. Specify true to create a unique index. The default value is false.
    name string The name of the index. If unspecified, MongoDB generates an index name by concatenating the names of the indexed fields and the sort order.
    sparse Boolean If true, the index only references documents with the specified field. These indexes use less space but behave differently in some situations (particularly sorts). The default value is false.
    expireAfterSeconds integer Specifies a value, in seconds, as a TTL to control how long MongoDB retains documents in this collection.
    weights document The weight is a number ranging from 1 to 99,999 and denotes the significance of the field relative to the other indexed fields in terms of the score.
    default_language string For a text index, the language that determines the list of stop words and the rules for the stemmer and tokenizer. The default value is English.
    language_override string For a text index, specify the name of the field in the document that contains, the language to override the default language. The default value is language.

    The dropIndex() method

    You can drop a particular index using the dropIndex() method of MongoDB.

    Syntax

    The basic syntax of DropIndex() method is as follows().

    >db.COLLECTION_NAME.dropIndex({KEY:1})
    

    Here, “key” is the name of the file on which you want to remove an existing index. Instead of the index specification document (above syntax), you can also specify the name of the index directly as:

    dropIndex("name_of_the_index")
    

    Example

    > db.mycol.dropIndex({"title":1})
    {
    	"ok" : 0,
    	"errmsg" : "can''t find index with key: { title: 1.0 }",
    	"code" : 27,
    	"codeName" : "IndexNotFound"
    }
    

    The dropIndexes() method

    This method deletes multiple (specified) indexes on a collection.

    Syntax

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

    >db.COLLECTION_NAME.dropIndexes()
    

    Example

    Assume we have created 2 indexes in the named mycol collection as shown below −

    > db.mycol.createIndex({"title":1,"description":-1})
    

    Following example removes the above created indexes of mycol −

    >db.mycol.dropIndexes({"title":1,"description":-1})
    { "nIndexesWas" : 2, "ok" : 1 }
    >
    

    The getIndexes() method

    This method returns the description of all the indexes int the collection.

    Syntax

    Following is the basic syntax od the getIndexes() method −

    db.COLLECTION_NAME.getIndexes()
    

    Example

    Assume we have created 2 indexes in the named mycol collection as shown below −

    > db.mycol.createIndex({"title":1,"description":-1})
    

    Following example retrieves all the indexes in the collection mycol −

    > db.mycol.getIndexes()
    [
    	{
    		"v" : 2,
    		"key" : {
    			"_id" : 1
    		},
    		"name" : "_id_",
    		"ns" : "test.mycol"
    	},
    	{
    		"v" : 2,
    		"key" : {
    			"title" : 1,
    			"description" : -1
    		},
    		"name" : "title_1_description_-1",
    		"ns" : "test.mycol"
    	}
    ]
    >
    

    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 – Delete Document nhận dự án làm có lương

    MongoDB – Delete Document



    In this chapter, we will learn how to delete a document using MongoDB.

    The remove() Method

    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.

    Syntax

    Basic syntax of remove() method is as follows −

    >db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
    

    Example

    Consider the mycol collection has the following data.

    {_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},
    {_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},
    {_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}
    

    Following example will remove all the documents whose title is ”MongoDB Overview”.

    >db.mycol.remove({''title'':''MongoDB Overview''})
    WriteResult({"nRemoved" : 1})
    > db.mycol.find()
    {"_id" : ObjectId("507f191e810c19729de860e2"), "title" : "NoSQL Overview" }
    {"_id" : ObjectId("507f191e810c19729de860e3"), "title" : "Tutorials Point Overview" }
    

    Remove Only One

    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)
    

    Remove All Documents

    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({})
    WriteResult({ "nRemoved" : 2 })
    > db.mycol.find()
    >
    

    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 – Query Document nhận dự án làm có lương

    MongoDB – Query Document



    In this chapter, we will learn how to query document from MongoDB collection.

    The find() Method

    To query data from MongoDB collection, you need to use MongoDB”s find() method.

    Syntax

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

    >db.COLLECTION_NAME.find()
    

    find() method will display all the documents in a non-structured way.

    Example

    Assume we have created a collection named mycol as −

    > use sampleDB
    switched to db sampleDB
    > db.createCollection("mycol")
    { "ok" : 1 }
    >
    

    And inserted 3 documents in it using the insert() method as shown below −

    > db.mycol.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
    			}
    		]
    	}
    ])
    

    Following method retrieves all the documents in the collection −

    > db.mycol.find()
    { "_id" : ObjectId("5dd4e2cc0821d3b44607534c"), "title" : "MongoDB Overview", "description" : "MongoDB is no SQL database", "by" : "tutorials point", "url" : "http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
    { "_id" : ObjectId("5dd4e2cc0821d3b44607534d"), "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" : ISODate("2013-12-09T21:05:00Z"), "like" : 0 } ] }
    >
    

    The pretty() Method

    To display the results in a formatted way, you can use pretty() method.

    Syntax

    >db.COLLECTION_NAME.find().pretty()
    

    Example

    Following example retrieves all the documents from the collection named mycol and arranges them in an easy-to-read format.

    > db.mycol.find().pretty()
    {
    	"_id" : ObjectId("5dd4e2cc0821d3b44607534c"),
    	"title" : "MongoDB Overview",
    	"description" : "MongoDB is no SQL database",
    	"by" : "tutorials point",
    	"url" : "http://www.tutorialspoint.com",
    	"tags" : [
    		"mongodb",
    		"database",
    		"NoSQL"
    	],
    	"likes" : 100
    }
    {
    	"_id" : ObjectId("5dd4e2cc0821d3b44607534d"),
    	"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" : ISODate("2013-12-09T21:05:00Z"),
    			"like" : 0
    		}
    	]
    }
    

    The findOne() method

    Apart from the find() method, there is findOne() method, that returns only one document.

    Syntax

    >db.COLLECTIONNAME.findOne()
    

    Example

    Following example retrieves the document with title MongoDB Overview.

    > db.mycol.findOne({title: "MongoDB Overview"})
    {
    	"_id" : ObjectId("5dd6542170fb13eec3963bf0"),
    	"title" : "MongoDB Overview",
    	"description" : "MongoDB is no SQL database",
    	"by" : "tutorials point",
    	"url" : "http://www.tutorialspoint.com",
    	"tags" : [
    		"mongodb",
    		"database",
    		"NoSQL"
    	],
    	"likes" : 100
    }
    

    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>:{$eg;<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
    Values in an array {<key>:{$in:[<value1>, <value2>,……<valueN>]}} db.mycol.find({“name”:{$in:[“Raj”, “Ram”, “Raghu”]}}).pretty() Where name matches any of the value in :[“Raj”, “Ram”, “Raghu”]
    Values not in an array {<key>:{$nin:<value>}} db.mycol.find({“name”:{$nin:[“Ramu”, “Raghav”]}}).pretty() Where name values is not in the array :[“Ramu”, “Raghav”] or, doesn’t exist at all

    AND in MongoDB

    Syntax

    To query documents based on the AND condition, you need to use $and keyword. Following is the basic syntax of AND −

    >db.mycol.find({ $and: [ {<key1>:<value1>}, { <key2>:<value2>} ] })
    

    Example

    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("5dd4e2cc0821d3b44607534c"),
    	"title" : "MongoDB Overview",
    	"description" : "MongoDB is no SQL database",
    	"by" : "tutorials point",
    	"url" : "http://www.tutorialspoint.com",
    	"tags" : [
    		"mongodb",
    		"database",
    		"NoSQL"
    	],
    	"likes" : 100
    }
    >
    

    For the above given example, equivalent where clause will be ” where by = ”tutorials point” AND title = ”MongoDB Overview” ”. You can pass any number of key, value pairs in find clause.

    OR in MongoDB

    Syntax

    To query documents based on the OR condition, you need to use $or keyword. Following is the basic syntax of OR

    >db.mycol.find(
       {
          $or: [
             {key1: value1}, {key2:value2}
          ]
       }
    ).pretty()
    

    Example

    Following example will show all the tutorials written by ”tutorials point” or whose title is ”MongoDB Overview”.

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

    Using AND and OR Together

    Example

    The following example will 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"
    }
    >
    

    NOR in MongoDB

    Syntax

    To query documents based on the NOT condition, you need to use $not keyword. Following is the basic syntax of NOT

    >db.COLLECTION_NAME.find(
    	{
    		$not: [
    			{key1: value1}, {key2:value2}
    		]
    	}
    )
    

    Example

    Assume we have inserted 3 documents in the collection empDetails 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 will retrieve the document(s) whose first name is not “Radhika” and last name is not “Christopher”

    > db.empDetails.find(
    	{
    		$nor:[
    			40
    			{"First_Name": "Radhika"},
    			{"Last_Name": "Christopher"}
    		]
    	}
    ).pretty()
    {
    	"_id" : ObjectId("5dd631f270fb13eec3963bef"),
    	"First_Name" : "Fathima",
    	"Last_Name" : "Sheik",
    	"Age" : "24",
    	"e_mail" : "Fathima_Sheik.123@gmail.com",
    	"phone" : "9000054321"
    }
    

    NOT in MongoDB

    Syntax

    To query documents based on the NOT condition, you need to use $not keyword following is the basic syntax of NOT

    >db.COLLECTION_NAME.find(
    	{
    		$NOT: [
    			{key1: value1}, {key2:value2}
    		]
    	}
    ).pretty()
    

    Example

    Following example will retrieve the document(s) whose age is not greater than 25

    > db.empDetails.find( { "Age": { $not: { $gt: "25" } } } )
    {
    	"_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 – Projection nhận dự án làm có lương

    MongoDB – Projection



    In MongoDB, projection means selecting only the necessary data rather than selecting whole of the data of a document. If a document has 5 fields and you need to show only 3, then select only 3 fields from them.

    The find() Method

    MongoDB”s find() method, explained in 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.

    Syntax

    The basic syntax of find() method with projection is as follows −

    >db.COLLECTION_NAME.find({},{KEY:1})
    

    Example

    Consider the collection mycol has the following data −

    {_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},
    {_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},
    {_id : ObjectId("507f191e810c19729de860e3"), 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.


    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 – Replication nhận dự án làm có lương

    MongoDB – Replication



    Replication is the process of synchronizing data across multiple servers. Replication provides redundancy and increases data availability with multiple copies of data on different database servers. Replication protects a database from the loss of a single server. Replication also allows you to recover from hardware failure and service interruptions. With additional copies of the data, you can dedicate one to disaster recovery, reporting, or backup.

    Why Replication?

    • To keep your data safe
    • High (24*7) availability of data
    • Disaster recovery
    • No downtime for maintenance (like backups, index rebuilds, compaction)
    • Read scaling (extra copies to read from)
    • Replica set is transparent to the application

    How Replication Works in MongoDB

    MongoDB achieves replication by the use of replica set. A replica set is a group of mongod instances that host the same data set. In a replica, one node is primary node that receives all write operations. All other instances, such as secondaries, apply operations from the primary so that they have the same data set. Replica set can have only one primary node.

    • Replica set is a group of two or more nodes (generally minimum 3 nodes are required).

    • In a replica set, one node is primary node and remaining nodes are secondary.

    • All data replicates from primary to secondary node.

    • At the time of automatic failover or maintenance, election establishes for primary and a new primary node is elected.

    • After the recovery of failed node, it again join the replica set and works as a secondary node.

    A typical diagram of MongoDB replication is shown in which client application always interact with the primary node and the primary node then replicates the data to the secondary nodes.

    MongoDB Replication

    Replica Set Features

    • A cluster of N nodes
    • Any one node can be primary
    • All write operations go to primary
    • Automatic failover
    • Automatic recovery
    • Consensus election of primary

    Set Up a Replica Set

    In this tutorial, we will convert standalone MongoDB instance to a replica set. To convert to replica set, following are the steps −

    • Shutdown already running MongoDB server.

    • Start the MongoDB server by specifying — replSet option. Following is the basic syntax of –replSet −

    mongod --port "PORT" --dbpath "YOUR_DB_DATA_PATH" --replSet "REPLICA_SET_INSTANCE_NAME"
    

    Example

    mongod --port 27017 --dbpath "D:set upmongodbdata" --replSet rs0
    
    • It will start a mongod instance with the name rs0, on port 27017.

    • Now start the command prompt and connect to this mongod instance.

    • In Mongo client, issue the command rs.initiate() to initiate a new replica set.

    • To check the replica set configuration, issue the command rs.conf(). To check the status of replica set issue the command rs.status().

    Add Members to Replica Set

    To add members to replica set, start mongod instances on multiple machines. Now start a mongo client and issue a command rs.add().

    Syntax

    The basic syntax of rs.add() command is as follows −

    >rs.add(HOST_NAME:PORT)
    

    Example

    Suppose your mongod instance name is mongod1.net and it is running on port 27017. To add this instance to replica set, issue the command rs.add() in Mongo client.

    >rs.add("mongod1.net:27017")
    >
    

    You can add mongod instance to replica set only when you are connected to primary node. To check whether you are connected to primary or not, issue the command db.isMaster() in mongo client.


    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 – Aggregation nhận dự án làm có lương

    MongoDB – Aggregation



    Aggregations operations process data records and return computed results. Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result. In SQL count(*) and with group by is an equivalent of MongoDB aggregation.

    The aggregate() Method

    For the aggregation in MongoDB, you should use aggregate() method.

    Syntax

    Basic syntax of aggregate() method is as follows −

    >db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
    

    Example

    In the collection you have the following data −

    {
       _id: ObjectId(7df78ad8902c)
       title: ''MongoDB Overview'',
       description: ''MongoDB is no sql database'',
       by_user: ''tutorials point'',
       url: ''http://www.tutorialspoint.com'',
       tags: [''mongodb'', ''database'', ''NoSQL''],
       likes: 100
    },
    {
       _id: ObjectId(7df78ad8902d)
       title: ''NoSQL Overview'',
       description: ''No sql database is very fast'',
       by_user: ''tutorials point'',
       url: ''http://www.tutorialspoint.com'',
       tags: [''mongodb'', ''database'', ''NoSQL''],
       likes: 10
    },
    {
       _id: ObjectId(7df78ad8902e)
       title: ''Neo4j Overview'',
       description: ''Neo4j is no sql database'',
       by_user: ''Neo4j'',
       url: ''http://www.neo4j.com'',
       tags: [''neo4j'', ''database'', ''NoSQL''],
       likes: 750
    },
    

    Now from the above collection, if you want to display a list stating how many tutorials are written by each user, then you will use the following aggregate() method −

    > db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
    { "_id" : "tutorials point", "num_tutorial" : 2 }
    { "_id" : "Neo4j", "num_tutorial" : 1 }
    >
    

    Sql equivalent query for the above use case will be select by_user, count(*) from mycol group by by_user.

    In the above example, we have grouped documents by field by_user and on each occurrence of by user previous value of sum is incremented. Following is a list of available aggregation expressions.

    Expression Description Example
    $sum Sums up the defined value from all documents in the collection. db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$sum : “$likes”}}}])
    $avg Calculates the average of all given values from all documents in the collection. db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$avg : “$likes”}}}])
    $min Gets the minimum of the corresponding values from all documents in the collection. db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$min : “$likes”}}}])
    $max Gets the maximum of the corresponding values from all documents in the collection. db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$max : “$likes”}}}])
    $push Inserts the value to an array in the resulting document. db.mycol.aggregate([{$group : {_id : “$by_user”, url : {$push: “$url”}}}])
    $addToSet Inserts the value to an array in the resulting document but does not create duplicates. db.mycol.aggregate([{$group : {_id : “$by_user”, url : {$addToSet : “$url”}}}])
    $first Gets the first document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage. db.mycol.aggregate([{$group : {_id : “$by_user”, first_url : {$first : “$url”}}}])
    $last Gets the last document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage. db.mycol.aggregate([{$group : {_id : “$by_user”, last_url : {$last : “$url”}}}])

    Pipeline Concept

    In UNIX command, shell pipeline means the possibility to execute an operation on some input and use the output as the input for the next command and so on. MongoDB also supports same concept in aggregation framework. There is a set of possible stages and each of those is taken as a set of documents as an input and produces a resulting set of documents (or the final resulting JSON document at the end of the pipeline). This can then in turn be used for the next stage and so on.

    Following are the possible stages in aggregation framework −

    • $project − Used to select some specific fields from a collection.

    • $match − This is a filtering operation and thus this can reduce the amount of documents that are given as input to the next stage.

    • $group − This does the actual aggregation as discussed above.

    • $sort − Sorts the documents.

    • $skip − With this, it is possible to skip forward in the list of documents for a given amount of documents.

    • $limit − This limits the amount of documents to look at, by the given number starting from the current positions.

    • $unwind − This is used to unwind document that are using arrays. When using an array, the data is kind of pre-joined and this operation will be undone with this to have individual documents again. Thus with this stage we will increase the amount of documents for the next stage.


    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 – Sorting Records nhận dự án làm có lương

    MongoDB – Sort Records



    In this chapter, we will learn how to sort records in MongoDB.

    The sort() Method

    To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

    Syntax

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

    >db.COLLECTION_NAME.find().sort({KEY:1})
    

    Example

    Consider the collection myycol has the following data.

    {_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"}
    {_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"}
    {_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}
    

    Following example will display the documents sorted by title in the descending order.

    >db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})
    {"title":"Tutorials Point Overview"}
    {"title":"NoSQL Overview"}
    {"title":"MongoDB Overview"}
    >
    

    Please note, if you don”t specify the sorting preference, then sort() method will display the documents in ascending order.


    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 – Limiting Records nhận dự án làm có lương

    MongoDB – Limit Records



    In this chapter, we will learn how to limit records using MongoDB.

    The Limit() Method

    To limit the records in MongoDB, you need to use limit() method. The method accepts one number type argument, which is the number of documents that you want to be displayed.

    Syntax

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

    >db.COLLECTION_NAME.find().limit(NUMBER)
    

    Example

    Consider the collection myycol has the following data.

    {_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},
    {_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},
    {_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}
    

    Following example will display only two documents while querying the document.

    >db.mycol.find({},{"title":1,_id:0}).limit(2)
    {"title":"MongoDB Overview"}
    {"title":"NoSQL Overview"}
    >
    

    If you don”t specify the number argument in limit() method then it will display all documents from the collection.

    MongoDB Skip() Method

    Apart from limit() method, there is one more method skip() which also accepts number type argument and is used to skip the number of documents.

    Syntax

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

    >db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
    

    Example

    Following example will display only the second document.

    >db.mycol.find({},{"title":1,_id:0}).limit(1).skip(1)
    {"title":"NoSQL Overview"}
    >
    

    Please note, the default value in skip() method is 0.


    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