May 17, 2021 MongoDB
Environment configuration
If you want to use MongoDB in a Java program, you need to make sure that you have the Java environment and MongoDB JDBC drivers installed.
You can refer to the Java tutorial on this site to install java programs. Now let's check if you have the MongoDB JDBC driver installed.
To connect to the database, you need to specify the database name, and if the specified database does not exist, mongo automatically creates the database.
The Java code for connecting to the database is as follows:
import com.mongodb.MongoClient; import com.mongodb.MongoException; import com.mongodb.WriteConcern; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.DBCursor; import com.mongodb.ServerAddress; import java.util.Arrays; public class MongoDBJDBC{ public static void main( String args[] ){ try{ // 连接到 mongodb 服务 MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // 连接到数据库 DB db = mongoClient.getDB( "test" ); System.out.println("Connect to database successfully"); boolean auth = db.authenticate(myUserName, myPassword); System.out.println("Authentication: "+auth); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } }
Now let's compile the runr and create the database test.
You can change the path of MongoDB JDBC drive more in your real environment.
This example places the MongoDB JDBC launch package mongo-2.10.1.jar in the local directory:
$javac MongoDBJDBC.java $java -classpath ".:mongo-2.10.1.jar" MongoDBJDBC Connect to database successfully Authentication: true
If you're using a Window system, you can compile the executor by following these commands:
$javac MongoDBJDBC.java $java -classpath ".;mongo-2.10.1.jar" MongoDBJDBC Connect to database successfully Authentication: true
If the username and password are correct, the value of Autotication is true.
We can use com.mongodb .DB create collections using the creativeCollection() in the class
The code snippet is as follows:
import com.mongodb.MongoClient; import com.mongodb.MongoException; import com.mongodb.WriteConcern; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.DBCursor; import com.mongodb.ServerAddress; import java.util.Arrays; public class MongoDBJDBC{ public static void main( String args[] ){ try{ // 连接到 mongodb 服务 MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // 连接到数据库 DB db = mongoClient.getDB( "test" ); System.out.println("Connect to database successfully"); boolean auth = db.authenticate(myUserName, myPassword); System.out.println("Authentication: "+auth); DBCollection coll = db.createCollection("mycol"); System.out.println("Collection created successfully"); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } }
Compile and run the above program, the output is as follows:
Connect to database successfully Authentication: true Collection created successfully
We can use the getCollection() method of the com.mongodb.DBCollection class to get a collection
The code snippet is as follows:
import com.mongodb.MongoClient; import com.mongodb.MongoException; import com.mongodb.WriteConcern; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.DBCursor; import com.mongodb.ServerAddress; import java.util.Arrays; public class MongoDBJDBC{ public static void main( String args[] ){ try{ // 连接到 mongodb 服务 MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // 连接到数据库 DB db = mongoClient.getDB( "test" ); System.out.println("Connect to database successfully"); boolean auth = db.authenticate(myUserName, myPassword); System.out.println("Authentication: "+auth); DBCollection coll = db.createCollection("mycol"); System.out.println("Collection created successfully"); DBCollection coll = db.getCollection("mycol"); System.out.println("Collection mycol selected successfully"); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } }
Compile and run the above program, the output is as follows:
Connect to database successfully Authentication: true Collection created successfully Collection mycol selected successfully
We can insert a document using the insert() method of the com.mongodb.DBCollection class
The code snippet is as follows:
import com.mongodb.MongoClient; import com.mongodb.MongoException; import com.mongodb.WriteConcern; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.DBCursor; import com.mongodb.ServerAddress; import java.util.Arrays; public class MongoDBJDBC{ public static void main( String args[] ){ try{ // 连接到 mongodb 服务 MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // 连接到数据库 DB db = mongoClient.getDB( "test" ); System.out.println("Connect to database successfully"); boolean auth = db.authenticate(myUserName, myPassword); System.out.println("Authentication: "+auth); DBCollection coll = db.getCollection("mycol"); System.out.println("Collection mycol selected successfully"); BasicDBObject doc = new BasicDBObject("title", "MongoDB"). append("description", "database"). append("likes", 100). append("url", "//www.w3cschool.cn/mongodb/"). append("by", "w3cschool.cn"); coll.insert(doc); System.out.println("Document inserted successfully"); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } }
Compile and run the above program, the output is as follows:
Connect to database successfully Authentication: true Collection mycol selected successfully Document inserted successfully
We can use the find() method in the com.mongodb.DBCollection class to get all the documents in the collection.
This method returns a cursor, so you need to traverse it.
The code snippet is as follows:
import com.mongodb.MongoClient; import com.mongodb.MongoException; import com.mongodb.WriteConcern; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.DBCursor; import com.mongodb.ServerAddress; import java.util.Arrays; public class MongoDBJDBC{ public static void main( String args[] ){ try{ // 连接到 mongodb 服务 MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // 连接到数据库 DB db = mongoClient.getDB( "test" ); System.out.println("Connect to database successfully"); boolean auth = db.authenticate(myUserName, myPassword); System.out.println("Authentication: "+auth); DBCollection coll = db.getCollection("mycol"); System.out.println("Collection mycol selected successfully"); DBCursor cursor = coll.find(); int i=1; while (cursor.hasNext()) { System.out.println("Inserted Document: "+i); System.out.println(cursor.next()); i++; } }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } }
Compile and run the above program, the output is as follows:
Connect to database successfully Authentication: true Collection mycol selected successfully Inserted Document: 1 { "_id" : ObjectId(7df78ad8902c), "title": "MongoDB", "description": "database", "likes": 100, "url": "//www.w3cschool.cn/mongodb/", "by": "w3cschool.cn" }
You can update documents in the collection using the update() method in the com.mongodb.DBCollection class.
The code snippet is as follows:
import com.mongodb.MongoClient; import com.mongodb.MongoException; import com.mongodb.WriteConcern; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.DBCursor; import com.mongodb.ServerAddress; import java.util.Arrays; public class MongoDBJDBC{ public static void main( String args[] ){ try{ // 连接到Mongodb服务 MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // 连接到你的数据库 DB db = mongoClient.getDB( "test" ); System.out.println("Connect to database successfully"); boolean auth = db.authenticate(myUserName, myPassword); System.out.println("Authentication: "+auth); DBCollection coll = db.getCollection("mycol"); System.out.println("Collection mycol selected successfully"); DBCursor cursor = coll.find(); while (cursor.hasNext()) { DBObject updateDocument = cursor.next(); updateDocument.put("likes","200") coll.update(updateDocument); } System.out.println("Document updated successfully"); cursor = coll.find(); int i=1; while (cursor.hasNext()) { System.out.println("Updated Document: "+i); System.out.println(cursor.next()); i++; } }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } }
Compile and run the above program, the output is as follows:
Connect to database successfully Authentication: true Collection mycol selected successfully Document updated successfully Updated Document: 1 { "_id" : ObjectId(7df78ad8902c), "title": "MongoDB", "description": "database", "likes": 200, "url": "//www.w3cschool.cn/mongodb/", "by": "w3cschool.cn" }
To delete the first document in the collection, you first need to use the findOne() method in the com.mongodb.DBCollection class to get the first document, and then delete it using the remove method.
The code snippet is as follows:
import com.mongodb.MongoClient; import com.mongodb.MongoException; import com.mongodb.WriteConcern; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.DBCursor; import com.mongodb.ServerAddress; import java.util.Arrays; public class MongoDBJDBC{ public static void main( String args[] ){ try{ // 连接到Mongodb服务 MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // 连接到你的数据库 DB db = mongoClient.getDB( "test" ); System.out.println("Connect to database successfully"); boolean auth = db.authenticate(myUserName, myPassword); System.out.println("Authentication: "+auth); DBCollection coll = db.getCollection("mycol"); System.out.println("Collection mycol selected successfully"); DBObject myDoc = coll.findOne(); coll.remove(myDoc); DBCursor cursor = coll.find(); int i=1; while (cursor.hasNext()) { System.out.println("Inserted Document: "+i); System.out.println(cursor.next()); i++; } System.out.println("Document deleted successfully"); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } }
Compile and run the above program, the output is as follows:
Connect to database successfully Authentication: true Collection mycol selected successfully Document deleted successfully
You can also use save(), limit(), skip(), sort() and other methods to manipulate the MongoDB database.