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…

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索