Author: alien

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

    MongoDB – ObjectId



    We have been using MongoDB Object Id in all the previous chapters. In this chapter, we will understand the structure of ObjectId.

    An ObjectId is a 12-byte BSON type having the following structure −

    • The first 4 bytes representing the seconds since the unix epoch
    • The next 3 bytes are the machine identifier
    • The next 2 bytes consists of process id
    • The last 3 bytes are a random counter value

    MongoDB uses ObjectIds as the default value of _id field of each document, which is generated while the creation of any document. The complex combination of ObjectId makes all the _id fields unique.

    Creating New ObjectId

    To generate a new ObjectId use the following code −

    >newObjectId = ObjectId()
    

    The above statement returned the following uniquely generated id −

    ObjectId("5349b4ddd2781d08c09890f3")
    

    Instead of MongoDB generating the ObjectId, you can also provide a 12-byte id −

    >myObjectId = ObjectId("5349b4ddd2781d08c09890f4")
    

    Creating Timestamp of a Document

    Since the _id ObjectId by default stores the 4-byte timestamp, in most cases you do not need to store the creation time of any document. You can fetch the creation time of a document using getTimestamp method −

    >ObjectId("5349b4ddd2781d08c09890f4").getTimestamp()
    

    This will return the creation time of this document in ISO date format −

    ISODate("2014-04-12T21:49:17Z")
    

    Converting ObjectId to String

    In some cases, you may need the value of ObjectId in a string format. To convert the ObjectId in string, use the following code −

    >newObjectId.str
    

    The above code will return the string format of the Guid −

    5349b4ddd2781d08c09890f3
    

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

    MongoDB – Advanced Indexing



    we have inserted the following document in the collection named users as shown below −

    db.users.insert(
    	{
    		"address": {
    			"city": "Los Angeles",
    			"state": "California",
    			"pincode": "123"
    		},
    		"tags": [
    			"music",
    			"cricket",
    			"blogs"
    		],
    		"name": "Tom Benzamin"
    	}
    )
    

    The above document contains an address sub-document and a tags array.

    Indexing Array Fields

    Suppose we want to search user documents based on the user’s tags. For this, we will create an index on tags array in the collection.

    Creating an index on array in turn creates separate index entries for each of its fields. So in our case when we create an index on tags array, separate indexes will be created for its values music, cricket and blogs.

    To create an index on tags array, use the following code −

    >db.users.createIndex({"tags":1})
    {
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 2,
    "numIndexesAfter" : 3,
    "ok" : 1
    }
    >
    

    After creating the index, we can search on the tags field of the collection like this −

    > db.users.find({tags:"cricket"}).pretty()
    {
    	"_id" : ObjectId("5dd7c927f1dd4583e7103fdf"),
    	"address" : {
    		"city" : "Los Angeles",
    		"state" : "California",
    		"pincode" : "123"
    	},
    	"tags" : [
    		"music",
    		"cricket",
    		"blogs"
    	],
    	"name" : "Tom Benzamin"
    }
    >
    

    To verify that proper indexing is used, use the following explain command −

    >db.users.find({tags:"cricket"}).explain()
    

    This gives you the following result −

    {
    	"queryPlanner" : {
    		"plannerVersion" : 1,
    		"namespace" : "mydb.users",
    		"indexFilterSet" : false,
    		"parsedQuery" : {
    			"tags" : {
    				"$eq" : "cricket"
    			}
    		},
    		"queryHash" : "9D3B61A7",
    		"planCacheKey" : "04C9997B",
    		"winningPlan" : {
    			"stage" : "FETCH",
    			"inputStage" : {
    				"stage" : "IXSCAN",
    				"keyPattern" : {
    					"tags" : 1
    				},
    				"indexName" : "tags_1",
    				"isMultiKey" : false,
    				"multiKeyPaths" : {
    					"tags" : [ ]
    				},
    				"isUnique" : false,
    				"isSparse" : false,
    				"isPartial" : false,
    				"indexVersion" : 2,
    				"direction" : "forward",
    				"indexBounds" : {
    					"tags" : [
    						"["cricket", "cricket"]"
    					]
    				}
    			}
    		},
    		"rejectedPlans" : [ ]
    	},
    	"serverInfo" : {
    		"host" : "Krishna",
    		"port" : 27017,
    		"version" : "4.2.1",
    		"gitVersion" : "edf6d45851c0b9ee15548f0f847df141764a317e"
    	},
    	"ok" : 1
    }
    >
    

    The above command resulted in “cursor” : “BtreeCursor tags_1” which confirms that proper indexing is used.

    Indexing Sub-Document Fields

    Suppose that we want to search documents based on city, state and pincode fields. Since all these fields are part of address sub-document field, we will create an index on all the fields of the sub-document.

    For creating an index on all the three fields of the sub-document, use the following code −

    >db.users.createIndex({"address.city":1,"address.state":1,"address.pincode":1})
    {
    	"numIndexesBefore" : 4,
    	"numIndexesAfter" : 4,
    	"note" : "all indexes already exist",
    	"ok" : 1
    }
    >
    

    Once the index is created, we can search for any of the sub-document fields utilizing this index as follows −

    > db.users.find({"address.city":"Los Angeles"}).pretty()
    {
    	"_id" : ObjectId("5dd7c927f1dd4583e7103fdf"),
    	"address" : {
    		"city" : "Los Angeles",
    		"state" : "California",
    		"pincode" : "123"
    	},
    	"tags" : [
    		"music",
    		"cricket",
    		"blogs"
    	],
    	"name" : "Tom Benzamin"
    }
    

    Remember that the query expression has to follow the order of the index specified. So the index created above would support the following queries −

    >db.users.find({"address.city":"Los Angeles","address.state":"California"}).pretty()
    {
    	"_id" : ObjectId("5dd7c927f1dd4583e7103fdf"),
    	"address" : {
    		"city" : "Los Angeles",
    		"state" : "California",
    		"pincode" : "123"
    	},
    	"tags" : [
    		"music",
    		"cricket",
    		"blogs"
    	],
    	"name" : "Tom Benzamin"
    }
    >
    

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

    MongoDB – Analyzing Queries



    Analyzing queries is a very important aspect of measuring how effective the database and indexing design is. We will learn about the frequently used $explain and $hint queries.

    Using $explain

    The $explain operator provides information on the query, indexes used in a query and other statistics. It is very useful when analyzing how well your indexes are optimized.

    In the last chapter, we had already created an index for the users collection on fields gender and user_name using the following query −

    >db.users.createIndex({gender:1,user_name:1})
    {
    	"numIndexesBefore" : 2,
    	"numIndexesAfter" : 2,
    	"note" : "all indexes already exist",
    	"ok" : 1
    }
    

    We will now use $explain on the following query −

    >db.users.find({gender:"M"},{user_name:1,_id:0}).explain()
    

    The above explain() query returns the following analyzed result −

    {
    	"queryPlanner" : {
    		"plannerVersion" : 1,
    		"namespace" : "mydb.users",
    		"indexFilterSet" : false,
    		"parsedQuery" : {
    			"gender" : {
    				"$eq" : "M"
    			}
    		},
    		"queryHash" : "B4037D3C",
    		"planCacheKey" : "DEAAE17C",
    		"winningPlan" : {
    			"stage" : "PROJECTION_COVERED",
    			"transformBy" : {
    				"user_name" : 1,
    				"_id" : 0
    			},
    			"inputStage" : {
    				"stage" : "IXSCAN",
    				"keyPattern" : {
    					"gender" : 1,
    					"user_name" : 1
    				},
    				"indexName" : "gender_1_user_name_1",
    				"isMultiKey" : false,
    				"multiKeyPaths" : {
    					"gender" : [ ],
    					"user_name" : [ ]
    				},
    				"isUnique" : false,
    				"isSparse" : false,
    				"isPartial" : false,
    				"indexVersion" : 2,
    				"direction" : "forward",
    				"indexBounds" : {
    					"gender" : [
    						"["M", "M"]"
    					],
    					"user_name" : [
    						"[MinKey, MaxKey]"
    					]
    				}
    			}
    		},
    		"rejectedPlans" : [ ]
    	},
    	"serverInfo" : {
    		"host" : "Krishna",
    		"port" : 27017,
    		"version" : "4.2.1",
    		"gitVersion" : "edf6d45851c0b9ee15548f0f847df141764a317e"
    	},
    	"ok" : 1
    }
    

    We will now look at the fields in this result set −

    • The true value of indexOnly indicates that this query has used indexing.

    • The cursor field specifies the type of cursor used. BTreeCursor type indicates that an index was used and also gives the name of the index used. BasicCursor indicates that a full scan was made without using any indexes.

    • n indicates the number of documents matching returned.

    • nscannedObjects indicates the total number of documents scanned.

    • nscanned indicates the total number of documents or index entries scanned.

    Using $hint

    The $hint operator forces the query optimizer to use the specified index to run a query. This is particularly useful when you want to test performance of a query with different indexes. For example, the following query specifies the index on fields gender and user_name to be used for this query −

    >db.users.find({gender:"M"},{user_name:1,_id:0}).hint({gender:1,user_name:1})
    { "user_name" : "tombenzamin" }
    

    To analyze the above query using $explain −

    >db.users.find({gender:"M"},{user_name:1,_id:0}).hint({gender:1,user_name:1}).explain()
    

    Which gives you the following result −

    {
    	"queryPlanner" : {
    		"plannerVersion" : 1,
    		"namespace" : "mydb.users",
    		"indexFilterSet" : false,
    		"parsedQuery" : {
    			"gender" : {
    				"$eq" : "M"
    			}
    		},
    		"queryHash" : "B4037D3C",
    		"planCacheKey" : "DEAAE17C",
    		"winningPlan" : {
    			"stage" : "PROJECTION_COVERED",
    			"transformBy" : {
    				"user_name" : 1,
    				"_id" : 0
    			},
    			"inputStage" : {
    				"stage" : "IXSCAN",
    				"keyPattern" : {
    					"gender" : 1,
    					"user_name" : 1
    				},
    				"indexName" : "gender_1_user_name_1",
    				"isMultiKey" : false,
    				"multiKeyPaths" : {
    					"gender" : [ ],
    					"user_name" : [ ]
    				},
    				"isUnique" : false,
    				"isSparse" : false,
    				"isPartial" : false,
    				"indexVersion" : 2,
    				"direction" : "forward",
    				"indexBounds" : {
    					"gender" : [
    						"["M", "M"]"
    					],
    					"user_name" : [
    						"[MinKey, MaxKey]"
    					]
    				}
    			}
    		},
    		"rejectedPlans" : [ ]
    	},
    	"serverInfo" : {
    		"host" : "Krishna",
    		"port" : 27017,
    		"version" : "4.2.1",
    		109
    		"gitVersion" : "edf6d45851c0b9ee15548f0f847df141764a317e"
    	},
    	"ok" : 1
    }
    

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

    MongoDB – Atomic Operations



    Model Data for Atomic Operations

    The recommended approach to maintain atomicity would be to keep all the related information, which is frequently updated together in a single document using embedded documents. This would make sure that all the updates for a single document are atomic.

    Assume we have created a collection with name productDetails and inserted a documents in it as shown below −

    >db.createCollection("products")
    { "ok" : 1 }
    > db.productDetails.insert(
    	{
    		"_id":1,
    		"product_name": "Samsung S3",
    		"category": "mobiles",
    		"product_total": 5,
    		"product_available": 3,
    		"product_bought_by": [
    			{
    				"customer": "john",
    				"date": "7-Jan-2014"
    			},
    			{
    				"customer": "mark",
    				"date": "8-Jan-2014"
    			}
    		]
    	}
    )
    WriteResult({ "nInserted" : 1 })
    >
    

    In this document, we have embedded the information of the customer who buys the product in the product_bought_by field. Now, whenever a new customer buys the product, we will first check if the product is still available using product_available field. If available, we will reduce the value of product_available field as well as insert the new customer”s embedded document in the product_bought_by field. We will use findAndModify command for this functionality because it searches and updates the document in the same go.

    >db.products.findAndModify({
       query:{_id:2,product_available:{$gt:0}},
       update:{
          $inc:{product_available:-1},
          $push:{product_bought_by:{customer:"rob",date:"9-Jan-2014"}}
       }
    })
    

    Our approach of embedded document and using findAndModify query makes sure that the product purchase information is updated only if it the product is available. And the whole of this transaction being in the same query, is atomic.

    In contrast to this, consider the scenario where we may have kept the product availability and the information on who has bought the product, separately. In this case, we will first check if the product is available using the first query. Then in the second query we will update the purchase information. However, it is possible that between the executions of these two queries, some other user has purchased the product and it is no more available. Without knowing this, our second query will update the purchase information based on the result of our first query. This will make the database inconsistent because we have sold a product which is not available.


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

    MongoDB – Covered Queries



    In this chapter, we will learn about covered queries.

    What is a Covered Query?

    As per the official MongoDB documentation, a covered query is a query in which −

    • All the fields in the query are part of an index.
    • All the fields returned in the query are in the same index.

    Since all the fields present in the query are part of an index, MongoDB matches the query conditions and returns the result using the same index without actually looking inside the documents. Since indexes are present in RAM, fetching data from indexes is much faster as compared to fetching data by scanning documents.

    Using Covered Queries

    To test covered queries, consider the following document in the users collection −

    {
       "_id": ObjectId("53402597d852426020000003"),
       "contact": "987654321",
       "dob": "01-01-1991",
       "gender": "M",
       "name": "Tom Benzamin",
       "user_name": "tombenzamin"
    }
    

    We will first create a compound index for the users collection on the fields gender and user_name using the following query −

    >db.users.createIndex({gender:1,user_name:1})
    {
    	"createdCollectionAutomatically" : false,
    	"numIndexesBefore" : 1,
    	"numIndexesAfter" : 2,
    	"ok" : 1
    }
    

    Now, this index will cover the following query −

    >db.users.find({gender:"M"},{user_name:1,_id:0})
    { "user_name" : "tombenzamin" }
    

    That is to say that for the above query, MongoDB would not go looking into database documents. Instead it would fetch the required data from indexed data which is very fast.

    Since our index does not include _id field, we have explicitly excluded it from result set of our query, as MongoDB by default returns _id field in every query. So the following query would not have been covered inside the index created above −

    >db.users.find({gender:"M"},{user_name:1})
    { "_id" : ObjectId("53402597d852426020000003"), "user_name" : "tombenzamin" }
    

    Lastly, remember that an index cannot cover a query if −

    • Any of the indexed fields is an array
    • Any of the indexed fields is a subdocument

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

    MongoDB – Relationships



    Relationships in MongoDB represent how various documents are logically related to each other. Relationships can be modeled via Embedded and Referenced approaches. Such relationships can be either 1:1, 1:N, N:1 or N:N.

    Let us consider the case of storing addresses for users. So, one user can have multiple addresses making this a 1:N relationship.

    Following is the sample document structure of user document −

    {
       "_id":ObjectId("52ffc33cd85242f436000001"),
       "name": "Tom Hanks",
       "contact": "987654321",
       "dob": "01-01-1991"
    }
    

    Following is the sample document structure of address document −

    {
       "_id":ObjectId("52ffc4a5d85242602e000000"),
       "building": "22 A, Indiana Apt",
       "pincode": 123456,
       "city": "Los Angeles",
       "state": "California"
    }
    

    Modeling Embedded Relationships

    In the embedded approach, we will embed the address document inside the user document.

    > db.users.insert({
    	{
    		"_id":ObjectId("52ffc33cd85242f436000001"),
    		"contact": "987654321",
    		"dob": "01-01-1991",
    		"name": "Tom Benzamin",
    		"address": [
    			{
    				"building": "22 A, Indiana Apt",
    				"pincode": 123456,
    				"city": "Los Angeles",
    				"state": "California"
    			},
    			{
    				"building": "170 A, Acropolis Apt",
    				"pincode": 456789,
    				"city": "Chicago",
    				"state": "Illinois"
    			}
    		]
    	}
    })
    

    This approach maintains all the related data in a single document, which makes it easy to retrieve and maintain. The whole document can be retrieved in a single query such as −

    >db.users.findOne({"name":"Tom Benzamin"},{"address":1})
    

    Note that in the above query, db and users are the database and collection respectively.

    The drawback is that if the embedded document keeps on growing too much in size, it can impact the read/write performance.

    Modeling Referenced Relationships

    This is the approach of designing normalized relationship. In this approach, both the user and address documents will be maintained separately but the user document will contain a field that will reference the address document”s id field.

    {
       "_id":ObjectId("52ffc33cd85242f436000001"),
       "contact": "987654321",
       "dob": "01-01-1991",
       "name": "Tom Benzamin",
       "address_ids": [
          ObjectId("52ffc4a5d85242602e000000"),
          ObjectId("52ffc4a5d85242602e000001")
       ]
    }
    

    As shown above, the user document contains the array field address_ids which contains ObjectIds of corresponding addresses. Using these ObjectIds, we can query the address documents and get address details from there. With this approach, we will need two queries: first to fetch the address_ids fields from user document and second to fetch these addresses from address collection.

    >var result = db.users.findOne({"name":"Tom Benzamin"},{"address_ids":1})
    >var addresses = db.address.find({"_id":{"$in":result["address_ids"]}})
    

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

    MongoDB – Database References



    As seen in the last chapter of MongoDB relationships, to implement a normalized database structure in MongoDB, we use the concept of Referenced Relationships also referred to as Manual References in which we manually store the referenced document”s id inside other document. However, in cases where a document contains references from different collections, we can use MongoDB DBRefs.

    DBRefs vs Manual References

    As an example scenario, where we would use DBRefs instead of manual references, consider a database where we are storing different types of addresses (home, office, mailing, etc.) in different collections (address_home, address_office, address_mailing, etc). Now, when a user collection”s document references an address, it also needs to specify which collection to look into based on the address type. In such scenarios where a document references documents from many collections, we should use DBRefs.

    Using DBRefs

    There are three fields in DBRefs −

    • $ref − This field specifies the collection of the referenced document

    • $id − This field specifies the _id field of the referenced document

    • $db − This is an optional field and contains the name of the database in which the referenced document lies

    Consider a sample user document having DBRef field address as shown in the code snippet −

    {
       "_id":ObjectId("53402597d852426020000002"),
       "address": {
       "$ref": "address_home",
       "$id": ObjectId("534009e4d852427820000002"),
       "$db": "tutorialspoint"},
       "contact": "987654321",
       "dob": "01-01-1991",
       "name": "Tom Benzamin"
    }
    

    The address DBRef field here specifies that the referenced address document lies in address_home collection under tutorialspoint database and has an id of 534009e4d852427820000002.

    The following code dynamically looks in the collection specified by $ref parameter (address_home in our case) for a document with id as specified by $id parameter in DBRef.

    >var user = db.users.findOne({"name":"Tom Benzamin"})
    >var dbRef = user.address
    >db[dbRef.$ref].findOne({"_id":(dbRef.$id)})
    

    The above code returns the following address document present in address_home collection −

    {
       "_id" : ObjectId("534009e4d852427820000002"),
       "building" : "22 A, Indiana Apt",
       "pincode" : 123456,
       "city" : "Los Angeles",
       "state" : "California"
    }
    

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

    MongoDB – Java



    In this chapter, we will learn how to set up MongoDB CLIENT.

    Installation

    Before you start using MongoDB in your Java programs, you need to make sure that you have MongoDB CLIENT and Java set up on the machine. You can check Java tutorial for Java installation on your machine. Now, let us check how to set up MongoDB CLIENT.

    • You need to download the jar mongodb-driver-3.11.2.jar and its dependency mongodb-driver-core-3.11.2.jar.. Make sure to download the latest release of these jar files.

    • You need to include the downloaded jar files into your classpath.

    Connect to Database

    To connect database, you need to specify the database name, if the database doesn”t exist then MongoDB creates it automatically.

    Following is the code snippet to connect to the database −

    import com.mongodb.client.MongoDatabase;
    import com.mongodb.MongoClient;
    import com.mongodb.MongoCredential;
    public class ConnectToDB {
    
       public static void main( String args[] ) {
    
          // Creating a Mongo client
          MongoClient mongo = new MongoClient( "localhost" , 27017 );
    
          // Creating Credentials
          MongoCredential credential;
          credential = MongoCredential.createCredential("sampleUser", "myDb",
             "password".toCharArray());
          System.out.println("Connected to the database successfully");
    
          // Accessing the database
          MongoDatabase database = mongo.getDatabase("myDb");
          System.out.println("Credentials ::"+ credential);
       }
    }
    

    Now, let”s compile and run the above program to create our database myDb as shown below.

    $javac ConnectToDB.java
    $java ConnectToDB
    

    On executing, the above program gives you the following output.

    Connected to the database successfully
    Credentials ::MongoCredential{
       mechanism = null,
       userName = ''sampleUser'',
       source = ''myDb'',
       password = <hidden>,
       mechanismProperties = {}
    }
    

    Create a Collection

    To create a collection, createCollection() method of com.mongodb.client.MongoDatabase class is used.

    Following is the code snippet to create a collection −

    import com.mongodb.client.MongoDatabase;
    import com.mongodb.MongoClient;
    import com.mongodb.MongoCredential;
    public class CreatingCollection {
    
       public static void main( String args[] ) {
    
          // Creating a Mongo client
          MongoClient mongo = new MongoClient( "localhost" , 27017 );
    
          // Creating Credentials
          MongoCredential credential;
          credential = MongoCredential.createCredential("sampleUser", "myDb",
             "password".toCharArray());
          System.out.println("Connected to the database successfully");
    
          //Accessing the database
          MongoDatabase database = mongo.getDatabase("myDb");
    
          //Creating a collection
          database.createCollection("sampleCollection");
          System.out.println("Collection created successfully");
       }
    }
    

    On compiling, the above program gives you the following result −

    Connected to the database successfully
    Collection created successfully
    

    Getting/Selecting a Collection

    To get/select a collection from the database, getCollection() method of com.mongodb.client.MongoDatabase class is used.

    Following is the program to get/select a collection −

    import com.mongodb.client.MongoCollection;
    import com.mongodb.client.MongoDatabase;
    import org.bson.Document;
    import com.mongodb.MongoClient;
    import com.mongodb.MongoCredential;
    public class selectingCollection {
    
       public static void main( String args[] ) {
    
          // Creating a Mongo client
          MongoClient mongo = new MongoClient( "localhost" , 27017 );
    
          // Creating Credentials
          MongoCredential credential;
          credential = MongoCredential.createCredential("sampleUser", "myDb",
             "password".toCharArray());
          System.out.println("Connected to the database successfully");
    
          // Accessing the database
          MongoDatabase database = mongo.getDatabase("myDb");
    
          // Creating a collection
          System.out.println("Collection created successfully");
          // Retrieving a collection
          MongoCollection<Document> collection = database.getCollection("myCollection");
          System.out.println("Collection myCollection selected successfully");
       }
    }
    

    On compiling, the above program gives you the following result −

    Connected to the database successfully
    Collection created successfully
    Collection myCollection selected successfully
    

    Insert a Document

    To insert a document into MongoDB, insert() method of com.mongodb.client.MongoCollection class is used.

    Following is the code snippet to insert a document −

    import com.mongodb.client.MongoCollection;
    import com.mongodb.client.MongoDatabase;
    import org.bson.Document;
    import com.mongodb.MongoClient;
    public class InsertingDocument {
    	public static void main( String args[] ) {
    
    	// Creating a Mongo client
    	MongoClient mongo = new MongoClient( "localhost" , 27017 );
    
    	// Accessing the database
    	MongoDatabase database = mongo.getDatabase("myDb");
    
    	// Creating a collection
    	database.createCollection("sampleCollection");
    	System.out.println("Collection created successfully");
    
    	// Retrieving a collection
    	MongoCollection<Document> collection = database.getCollection("sampleCollection");
    	System.out.println("Collection sampleCollection selected successfully");
    	Document document = new Document("title", "MongoDB")
    	.append("description", "database")
    	.append("likes", 100)
    	.append("url", "http://www.tutorialspoint.com/mongodb/")
    	.append("by", "tutorials point");
    
    	//Inserting document into the collection
    	collection.insertOne(document);
    	System.out.println("Document inserted successfully");
    }
    

    On compiling, the above program gives you the following result −

    Connected to the database successfully
    Collection sampleCollection selected successfully
    Document inserted successfully
    

    Retrieve All Documents

    To select all documents from the collection, find() method of com.mongodb.client.MongoCollection class is used. This method returns a cursor, so you need to iterate this cursor.

    Following is the program to select all documents −

    import com.mongodb.client.FindIterable;
    import com.mongodb.client.MongoCollection;
    import com.mongodb.client.MongoDatabase;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import org.bson.Document;
    import com.mongodb.MongoClient;
    import com.mongodb.MongoCredential;
    public class RetrievingAllDocuments {
    	public static void main( String args[] ) {
    
    		// Creating a Mongo client
    		MongoClient mongo = new MongoClient( "localhost" , 27017 );
    
    		// Creating Credentials
    		MongoCredential credential;
    		credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray());
    		System.out.println("Connected to the database successfully");
    
    		// Accessing the database
    		MongoDatabase database = mongo.getDatabase("myDb");
    
    		// Retrieving a collection
    		MongoCollection<Document> collection = database.getCollection("sampleCollection");
    		System.out.println("Collection sampleCollection selected successfully");
    		Document document1 = new Document("title", "MongoDB")
    		.append("description", "database")
    		.append("likes", 100)
    		.append("url", "http://www.tutorialspoint.com/mongodb/")
    		.append("by", "tutorials point");
    		Document document2 = new Document("title", "RethinkDB")
    		.append("description", "database")
    		.append("likes", 200)
    		.append("url", "http://www.tutorialspoint.com/rethinkdb/")
    		.append("by", "tutorials point");
    		List<Document> list = new ArrayList<Document>();
    		list.add(document1);
    		list.add(document2);
    		collection.insertMany(list);
    		// Getting the iterable object
    		FindIterable<Document> iterDoc = collection.find();
    		int i = 1;
    		// Getting the iterator
    		Iterator it = iterDoc.iterator();
    		while (it.hasNext()) {
    			System.out.println(it.next());
    			i++;
    		}
    	}
    }
    

    On compiling, the above program gives you the following result −

    Connected to the database successfully
    Collection sampleCollection selected successfully
    Document{{_id=5dce4e9ff68a9c2449e197b2, title=MongoDB, description=database, likes=100, url=http://www.tutorialspoint.com/mongodb/, by=tutorials point}}
    Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.tutorialspoint.com/rethinkdb/, by=tutorials point}}
    

    Update Document

    To update a document from the collection, updateOne() method of com.mongodb.client.MongoCollection class is used.

    Following is the program to select the first document −

    import com.mongodb.client.FindIterable;
    import com.mongodb.client.MongoCollection;
    import com.mongodb.client.MongoDatabase;
    import com.mongodb.client.model.Filters;
    import com.mongodb.client.model.Updates;
    import java.util.Iterator;
    import org.bson.Document;
    import com.mongodb.MongoClient;
    import com.mongodb.MongoCredential;
    public class UpdatingDocuments {
    
       public static void main( String args[] ) {
    
          // Creating a Mongo client
          MongoClient mongo = new MongoClient( "localhost" , 27017 );
    
          // Creating Credentials
          MongoCredential credential;
          credential = MongoCredential.createCredential("sampleUser", "myDb",
             "password".toCharArray());
          System.out.println("Connected to the database successfully");
    
          // Accessing the database
          MongoDatabase database = mongo.getDatabase("myDb");
          // Retrieving a collection
          MongoCollection<Document> collection = database.getCollection("sampleCollection");
          System.out.println("Collection myCollection selected successfully");
          collection.updateOne(Filters.eq("title", 1), Updates.set("likes", 150));
          System.out.println("Document update successfully...");
    
          // Retrieving the documents after updation
          // Getting the iterable object
          FindIterable<Document> iterDoc = collection.find();
          int i = 1;
          // Getting the iterator
          Iterator it = iterDoc.iterator();
          while (it.hasNext()) {
             System.out.println(it.next());
             i++;
          }
       }
    }
    

    On compiling, the above program gives you the following result −

    Connected to the database successfully
    Collection myCollection selected successfully
    Document update successfully...
    Document{{_id=5dce4e9ff68a9c2449e197b2, title=MongoDB, description=database, likes=100, url=http://www.tutorialspoint.com/mongodb/, by=tutorials point}}
    Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.tutorialspoint.com/rethinkdb/, by=tutorials point}}
    

    Delete a Document

    To delete a document from the collection, you need to use the deleteOne() method of the com.mongodb.client.MongoCollection class.

    Following is the program to delete a document −

    import com.mongodb.client.FindIterable;
    import com.mongodb.client.MongoCollection;
    import com.mongodb.client.MongoDatabase;
    import com.mongodb.client.model.Filters;
    import java.util.Iterator;
    import org.bson.Document;
    import com.mongodb.MongoClient;
    import com.mongodb.MongoCredential;
    public class DeletingDocuments {
    
       public static void main( String args[] ) {
    
          // Creating a Mongo client
          MongoClient mongo = new MongoClient( "localhost" , 27017 );
    
          // Creating Credentials
          MongoCredential credential;
          credential = MongoCredential.createCredential("sampleUser", "myDb",
             "password".toCharArray());
          System.out.println("Connected to the database successfully");
    
          // Accessing the database
          MongoDatabase database = mongo.getDatabase("myDb");
          // Retrieving a collection
          MongoCollection<Document> collection = database.getCollection("sampleCollection");
          System.out.println("Collection sampleCollection selected successfully");
          // Deleting the documents
          collection.deleteOne(Filters.eq("title", "MongoDB"));
          System.out.println("Document deleted successfully...");
    
          // Retrieving the documents after updation
          // Getting the iterable object
          FindIterable<Document> iterDoc = collection.find();
          int i = 1;
          // Getting the iterator
          Iterator it = iterDoc.iterator();
          while (it.hasNext()) {
             System.out.println(it.next());
             i++;
          }
       }
    }
    

    On compiling, the above program gives you the following result −

    Connected to the database successfully
    Collection sampleCollection selected successfully
    Document deleted successfully...
    Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.tutorialspoint.com/rethinkdb/, by=tutorials point}}
    

    Dropping a Collection

    To drop a collection from a database, you need to use the drop() method of the com.mongodb.client.MongoCollection class.

    Following is the program to delete a collection −

    import com.mongodb.client.MongoCollection;
    import com.mongodb.client.MongoDatabase;
    import org.bson.Document;
    import com.mongodb.MongoClient;
    import com.mongodb.MongoCredential;
    public class DropingCollection {
    
       public static void main( String args[] ) {
          // Creating a Mongo client
          MongoClient mongo = new MongoClient( "localhost" , 27017 );
          // Creating Credentials
          MongoCredential credential;
          credential = MongoCredential.createCredential("sampleUser", "myDb",
             "password".toCharArray());
          System.out.println("Connected to the database successfully");
    
          // Accessing the database
          MongoDatabase database = mongo.getDatabase("myDb");
    
          // Creating a collection
          System.out.println("Collections created successfully");
          // Retrieving a collection
          MongoCollection<Document> collection = database.getCollection("sampleCollection");
          // Dropping a Collection
          collection.drop();
          System.out.println("Collection dropped successfully");
       }
    }
    

    On compiling, the above program gives you the following result −

    Connected to the database successfully
    Collection sampleCollection selected successfully
    Collection dropped successfully
    

    Listing All the Collections

    To list all the collections in a database, you need to use the listCollectionNames() method of the com.mongodb.client.MongoDatabase class.

    Following is the program to list all the collections of a database −

    import com.mongodb.client.MongoDatabase;
    import com.mongodb.MongoClient;
    import com.mongodb.MongoCredential;
    public class ListOfCollection {
    
       public static void main( String args[] ) {
    
          // Creating a Mongo client
          MongoClient mongo = new MongoClient( "localhost" , 27017 );
          // Creating Credentials
          MongoCredential credential;
          credential = MongoCredential.createCredential("sampleUser", "myDb",
             "password".toCharArray());
          System.out.println("Connected to the database successfully");
    
          // Accessing the database
          MongoDatabase database = mongo.getDatabase("myDb");
          System.out.println("Collection created successfully");
          for (String name : database.listCollectionNames()) {
             System.out.println(name);
          }
       }
    }
    

    On compiling, the above program gives you the following result −

    Connected to the database successfully
    Collection created successfully
    myCollection
    myCollection1
    myCollection5
    

    Remaining MongoDB methods save(), limit(), skip(), sort() etc. work same as explained in the subsequent tutorial.


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

    MongoDB – PHP



    To use MongoDB with PHP, you need to use MongoDB PHP driver. Download the driver from the url . Make sure to download the latest release of it. Now unzip the archive and put php_mongo.dll in your PHP extension directory (“ext” by default) and add the following line to your php.ini file −

    extension = php_mongo.dll
    

    Make a Connection and Select a Database

    To make a connection, you need to specify the database name, if the database doesn”t exist then MongoDB creates it automatically.

    Following is the code snippet to connect to the database −

    <?php
       // connect to mongodb
       $m = new MongoClient();
    
       echo "Connection to database successfully";
       // select a database
       $db = $m->mydb;
    
       echo "Database mydb selected";
    ?>
    

    When the program is executed, it will produce the following result −

    Connection to database successfully
    Database mydb selected
    

    Create a Collection

    Following is the code snippet to create a collection −

    <?php
       // connect to mongodb
       $m = new MongoClient();
       echo "Connection to database successfully";
    
       // select a database
       $db = $m->mydb;
       echo "Database mydb selected";
       $collection = $db->createCollection("mycol");
       echo "Collection created succsessfully";
    ?>
    

    When the program is executed, it will produce the following result −

    Connection to database successfully
    Database mydb selected
    Collection created succsessfully
    

    Insert a Document

    To insert a document into MongoDB, insert() method is used.

    Following is the code snippet to insert a document −

    <?php
       // connect to mongodb
       $m = new MongoClient();
       echo "Connection to database successfully";
    
       // select a database
       $db = $m->mydb;
       echo "Database mydb selected";
       $collection = $db->mycol;
       echo "Collection selected succsessfully";
    
       $document = array(
          "title" => "MongoDB",
          "description" => "database",
          "likes" => 100,
          "url" => "http://www.tutorialspoint.com/mongodb/",
          "by" => "tutorials point"
       );
    
       $collection->insert($document);
       echo "Document inserted successfully";
    ?>
    

    When the program is executed, it will produce the following result −

    Connection to database successfully
    Database mydb selected
    Collection selected succsessfully
    Document inserted successfully
    

    Find All Documents

    To select all documents from the collection, find() method is used.

    Following is the code snippet to select all documents −

    <?php
       // connect to mongodb
       $m = new MongoClient();
       echo "Connection to database successfully";
    
       // select a database
       $db = $m->mydb;
       echo "Database mydb selected";
       $collection = $db->mycol;
       echo "Collection selected succsessfully";
       $cursor = $collection->find();
       // iterate cursor to display title of documents
    
       foreach ($cursor as $document) {
          echo $document["title"] . "n";
       }
    ?>
    

    When the program is executed, it will produce the following result −

    Connection to database successfully
    Database mydb selected
    Collection selected succsessfully {
       "title": "MongoDB"
    }
    

    Update a Document

    To update a document, you need to use the update() method.

    In the following example, we will update the title of inserted document to MongoDB Tutorial. Following is the code snippet to update a document −

    <?php
       // connect to mongodb
       $m = new MongoClient();
       echo "Connection to database successfully";
    
       // select a database
       $db = $m->mydb;
       echo "Database mydb selected";
       $collection = $db->mycol;
       echo "Collection selected succsessfully";
       // now update the document
       $collection->update(array("title"=>"MongoDB"),
          array(''$set''=>array("title"=>"MongoDB Tutorial")));
       echo "Document updated successfully";
    
       // now display the updated document
       $cursor = $collection->find();
    
       // iterate cursor to display title of documents
       echo "Updated document";
    
       foreach ($cursor as $document) {
          echo $document["title"] . "n";
       }
    ?>
    

    When the program is executed, it will produce the following result −

    Connection to database successfully
    Database mydb selected
    Collection selected succsessfully
    Document updated successfully
    Updated document {
       "title": "MongoDB Tutorial"
    }
    

    Delete a Document

    To delete a document, you need to use remove() method.

    In the following example, we will remove the documents that has the title MongoDB Tutorial. Following is the code snippet to delete a document −

    <?php
       // connect to mongodb
       $m = new MongoClient();
       echo "Connection to database successfully";
    
       // select a database
       $db = $m->mydb;
       echo "Database mydb selected";
       $collection = $db->mycol;
       echo "Collection selected succsessfully";
    
       // now remove the document
       $collection->remove(array("title"=>"MongoDB Tutorial"),false);
       echo "Documents deleted successfully";
    
       // now display the available documents
       $cursor = $collection->find();
    
       // iterate cursor to display title of documents
       echo "Updated document";
    
       foreach ($cursor as $document) {
          echo $document["title"] . "n";
       }
    ?>
    

    When the program is executed, it will produce the following result −

    Connection to database successfully
    Database mydb selected
    Collection selected successfully
    Documents deleted successfully
    

    In the above example, the second parameter is boolean type and used for justOne field of remove() method.

    Remaining MongoDB methods findOne(), save(), limit(), skip(), sort() etc. works same as explained above.


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

    MongoDB – Create Backup



    In this chapter, we will see how to create a backup in MongoDB.

    Dump MongoDB Data

    To create backup of database in MongoDB, you should use mongodump command. This command will dump the entire data of your server into the dump directory. There are many options available by which you can limit the amount of data or create backup of your remote server.

    Syntax

    The basic syntax of mongodump command is as follows −

    >mongodump
    

    Example

    Start your mongod server. Assuming that your mongod server is running on the localhost and port 27017, open a command prompt and go to the bin directory of your mongodb instance and type the command mongodump

    Consider the mycol collection has the following data.

    >mongodump
    

    The command will connect to the server running at 127.0.0.1 and port 27017 and back all data of the server to directory /bin/dump/. Following is the output of the command −

    DB Stats

    Following is a list of available options that can be used with the mongodump command.

    Syntax Description Example
    mongodump –host HOST_NAME –port PORT_NUMBER This commmand will backup all databases of specified mongod instance. mongodump –host tutorialspoint.com –port 27017
    mongodump –dbpath DB_PATH –out BACKUP_DIRECTORY This command will backup only specified database at specified path. mongodump –dbpath /data/db/ –out /data/backup/
    mongodump –collection COLLECTION –db DB_NAME This command will backup only specified collection of specified database. mongodump –collection mycol –db test

    Restore data

    To restore backup data MongoDB”s mongorestore command is used. This command restores all of the data from the backup directory.

    Syntax

    The basic syntax of mongorestore command is −

    >mongorestore
    

    Following is the output of the command −

    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