MongoDB and Java Development
Environment configuration If you want to use MongoDB in a Java program, you need to ensure that the Java environment and the MongoDB JDBC driver have been installed. You can refer to the Java tutorial on this site to install the Java program. Now let’s check if you have the MongoDB JDBC driver installed. First you have to download mongo jar package, download address: https://github.com/mongodb/mongo-java-driver/downloads, Make sure to download the latest version. You need to include mongo.jar in your classpath. . Connect to database To connect to the database, you need to specify the database name. If the specified database does not exist, mongo will automatically create the database. Java to connect to the database 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{ // Connect to mongodb service MongoClient mongoClient = new MongoClient( “localhost”, 27017 ); // Connect to database 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 and run the program…