Quantcast
Channel: CodeSection,代码区,数据库(综合) - CodeSec
Viewing all articles
Browse latest Browse all 6262

Learn How to Update and Delete From a Collection using MongoDB

$
0
0

Learn How to Update and Delete From a Collection using MongoDB

In this chapter, we are going to use the MongoDB JDBC connection (explained in the previous article) in order to connect MongoDB database with JAVA. After successfully connecting MongoDB with JAVA, we are going to create a collection, insert, modify and delete documents into this collection through JAVA programming language.

MongoDbJdbcConnection.java

package com.eduonix.db; importcom.mongodb.DB; importcom.mongodb.MongoClient; public class MongoDbJdbcConnection { public static DBgetMongoDBConnection (String host, int port, String dBName){ DBdb = null; try { /**** Connect to the MongoDB ****/ // Since 2.10.0, uses MongoClient 27017 MongoClientmongodb= new MongoClient(host, port); /**** Get database ****/ // if database doesn't exists, MongoDB will create it for us db = mongodb.getDB(dBName); System.out.println("Connect to database is success "+db); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } return db; } }

MongoDB Creation, Selection and modification of a document in a collection

Using the class ‘MongoDbJdbcConnection.java’, we will be able to connect to MongoDB by simply calling the static method getMongoDBConnection which accepts three arguments i.e. host name, port number and database name. This method will return a DB class object. By using this DB object, we are going to first create and select a collection followed by the modification of a document in this collection through JAVA Programming.

Syntaxes To create a collection, we can use the ‘createCollection ()’ method of com.mongodb.DB class. To get or select a collection from the database, we can use the ‘getCollection ()’ method of com.mongodb.DBCollection class. To insert a document into MongoDB, we can use the ‘insert ()’ method of com.mongodb.DBCollection class. To modify or update a document into MongoDB, we can use the ‘update ()’ method of com.mongodb.DBCollection class.

MongoDbUpdateDemo.java

package com.eduonix.db; importcom.mongodb.BasicDBObject; importcom.mongodb.DB; importcom.mongodb.DBCollection; importcom.mongodb.DBCursor; importcom.mongodb.DBObject; public class MongoDbUpdateDemo { public static void main(String args[]){ String CollectionName ="MyCollection10"; DBdb = MongoDbJdbcConnection.getMongoDBConnection("localhost", 27017, "dbtest"); /** * Creating and Inserting Records in MongoDB. */ DBObjectdbObject = new BasicDBObject("title", "MongoDBTutorials").append("description", "No-SQL Database") .append("likes", 100000).append("url", "https://www.mongodb.com/").append("Tutorial", "Eduonix"); db.createCollection(CollectionName, dbObject); /** * Selecting Records from MongoDB */ DBCollectioncoll = db.getCollection(CollectionName); coll.insert(dbObject); //coll.insert(dbObject2); System.out.println("Collection has created successfully"); /** * Displaying available records. */ DBCursorcursor = coll.find(); int index = 1; while (cursor.hasNext()) { System.out.println("Inserted Document: " + index); System.out.println(cursor.next()); index++; } /** * Modify a Document present in a Collection. */ DBCursorcursor1 = coll.find(); DBObjectdbObjectQuery = new BasicDBObject("title", "MongoDBTutorials"); while (cursor1.hasNext()) { DBObjectupdateDocument = cursor1.next(); updateDocument.put("likes","9999999"); updateDocument.put("description","No-SQL Database with high performance!"); coll.update(dbObjectQuery,updateDocument); } System.out.println("Document has updated successfully"); DBCursorcursor2 = coll.find(); int i = 1; while (cursor2.hasNext()) { System.out.println("Updated Document: "+i); System.out.println(cursor2.next()); i++; } } }

Before executing this program, make sure that the MongoDB instance is running on your local or remote machine. Here, the MongoDB instance is running on the local machine at port 27017.

Explanation of Code Firstly, we are connecting the MongoDB client by passing three arguments to the static getMongoDBConnection method of ‘MongoDbJdbcConnection.java’ class. This will return a DB class instance of a MongoDB database into ‘db’ instance variable. Next, we are creating instance of ‘DBObject’ through ‘BasicDBObject’ class that helps to create the schema definition to be inserted in the collection. Next, we are creating collection through ‘db.createCollection (“MyCollection10”, dbObject);’ method. Next, we are going to select this collection ‘MyCollection10’ through ‘db.getCollection (“MyCollection10”);’ method which returns the instance into ‘coll’ instance variable. Through ‘coll’ instance variable, we can use ‘coll.insert (dbObject);’ to insert the DBObject instance which we have created before. At this step, a document has successfully inserted into the MongoDB. Now, we are using ‘DBCursor’ class which returns the cursor to iterate over the documents and display those documents present in the current collection through ‘DBCursor cursor = coll.find ();’ method. Next, we are again using ‘DBCursor’ class which returns the cursor to iterate over the documents and modify or update those documents present in the current collection through ‘coll.update (dbObjectQuery, updateDocument)’ method. Next, we are again using ‘DBCursor’ class which returns the cursor to iterate over the documents and display the modified documents present in the current collection through ‘DBCursor cursor = coll.find ();’ method.

Output

When we execute above JAVA program, it will connect to the MongoDB and do the creation, selection and retrieving operations on the collection ‘MyCollection10’ followed by the modification of a document present in this collection as shown on the console.

Feb 23, 2017 6:10:49 PMcom.mongodb.diagnostics.logging.JULLoggerlog INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500} Connect to database is success DB{name='dbtest'} Feb 23, 2017 6:10:50 PMcom.mongodb.diagnostics.logging.JULLoggerlog INFO: No server chosen by WritableServerSelector from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING}]}. Waitingfor 30000 msbeforetimingout Feb 23, 2017 6:10:50 PMcom.mongodb.diagnostics.logging.JULLoggerlog INFO: Opened connection [connectionId{localValue:1, serverValue:31}] to localhost:27017 Feb 23, 2017 6:10:50 PMcom.mongodb.diagnostics.logging.JULLoggerlog INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 10]}, minWireVersion=0, maxWireVersion=4, maxDocumentSize=16777216, roundTripTimeNanos=2824198} Feb 23, 2017 6:10:50 PMcom.mongodb.diagnostics.logging.JULLoggerlog INFO: Opened connection [connectionId{localValue:2, serverValue:32}] to localhost:27017 Collectionhascreatedsuccessfully InsertedDocument: 1 { "_id" : { "$oid" : "58af6bfa7d1fcb0fb0e5fa47"} , "title" : "MongoDBTutorials" , "description" : "No-SQL Database" , "likes" : 100000 , "url" : "https://www.mongodb.com/" , "Tutorial" : "Eduonix"} Documenthasupdatedsuccessfully UpdatedDocument: 1 { "_id" : { "$oid" : "58af6bfa7d1fcb0fb0e5fa47"} , "title" : "MongoDBTutorials" , "description" : "No-SQL Database with high performance!" , "likes"

Viewing all articles
Browse latest Browse all 6262

Trending Articles