MongoDB Java
环境配置
在Java程序中如果要使用MongoDB,你需要确保已经安装了Java环境及MongoDB JDBC 驱动。
你可以参考本站的Java教程来安装Java程序。现在让我们来检测你是否安装了 MongoDB JDBC 驱动。
你需要将mongo.jar包含在你的 classpath 中。。
连接数据库
连接数据库,你需要指定数据库名称,如果指定的数据库不存在,mongo会自动创建数据库。
连接数据库的Java代码如下:
importcom.mongodb.MongoClient;importcom.mongodb.MongoException;importcom.mongodb.WriteConcern;importcom.mongodb.DB;importcom.mongodb.DBCollection;importcom.mongodb.BasicDBObject;importcom.mongodb.DBObject;importcom.mongodb.DBCursor;importcom.mongodb.ServerAddress;importjava.util.Arrays;publicclassMongoDBJDBC{publicstaticvoidmain(Stringargs[]){try{// 连接到 mongodb 服务MongoClientmongoClient=newMongoClient("localhost",27017);// 连接到数据库DB db=mongoClient.getDB("test");System.out.println("Connect to database successfully");booleanauth=db.authenticate(myUserName,myPassword);System.out.println("Authentication: "+auth);}catch(Exceptione){System.err.println(e.getClass().getName()+": "+e.getMessage());}}}
现在,让我们来编译运行程序并创建数据库test。
你可以更加你的实际环境改变MongoDB JDBC驱动的路径。
本实例将MongoDB JDBC启动包 mongo-2.10.1.jar 放在本地目录下:
$javacMongoDBJDBC.java
$java-classpath".:mongo-2.10.1.jar"MongoDBJDBCConnectto database successfullyAuthentication:true
如果你使用的是Window系统,你可以按以下命令来编译执行程序:
$javacMongoDBJDBC.java
$java-classpath".;mongo-2.10.1.jar"MongoDBJDBCConnectto database successfullyAuthentication:true
如果用户名及密码正确,则Authentication 的值为true。
创建集合
我们可以使用com.mongodb.DB类中的createCollection()来创建集合
代码片段如下:
importcom.mongodb.MongoClient;importcom.mongodb.MongoException;importcom.mongodb.WriteConcern;importcom.mongodb.DB;importcom.mongodb.DBCollection;importcom.mongodb.BasicDBObject;importcom.mongodb.DBObject;importcom.mongodb.DBCursor;importcom.mongodb.ServerAddress;importjava.util.Arrays;publicclassMongoDBJDBC{publicstaticvoidmain(Stringargs[]){try{// 连接到 mongodb 服务MongoClientmongoClient=newMongoClient("localhost",27017);// 连接到数据库DB db=mongoClient.getDB("test");System.out.println("Connect to database successfully");booleanauth=db.authenticate(myUserName,myPassword);System.out.println("Authentication: "+auth);DBCollectioncoll=db.createCollection("mycol");System.out.println("Collection created successfully");}catch(Exceptione){System.err.println(e.getClass().getName()+": "+e.getMessage());}}}
编译运行以上程序,输出结果如下:
Connectto database successfullyAuthentication:trueCollectioncreated successfully
获取集合
我们可以使用com.mongodb.DBCollection类的 getCollection() 方法来获取一个集合
代码片段如下:
importcom.mongodb.MongoClient;importcom.mongodb.MongoException;importcom.mongodb.WriteConcern;importcom.mongodb.DB;importcom.mongodb.DBCollection;importcom.mongodb.BasicDBObject;importcom.mongodb.DBObject;importcom.mongodb.DBCursor;importcom.mongodb.ServerAddress;importjava.util.Arrays;publicclassMongoDBJDBC{publicstaticvoidmain(Stringargs[]){try{// 连接到 mongodb 服务MongoClientmongoClient=newMongoClient("localhost",27017);// 连接到数据库DB db=mongoClient.getDB("test");System.out.println("Connect to database successfully");booleanauth=db.authenticate(myUserName,myPassword);System.out.println("Authentication: "+auth);DBCollectioncoll=db.createCollection("mycol");System.out.println("Collection created successfully");DBCollectioncoll=db.getCollection("mycol");System.out.println("Collection mycol selected successfully");}catch(Exceptione){System.err.println(e.getClass().getName()+": "+e.getMessage());}}}
编译运行以上程序,输出结果如下:
Connectto database successfullyAuthentication:trueCollectioncreated successfullyCollectionmycol selected successfully
插入文档
我们可以使用com.mongodb.DBCollection类的 insert() 方法来插入一个文档
代码片段如下:
importcom.mongodb.MongoClient;importcom.mongodb.MongoException;importcom.mongodb.WriteConcern;importcom.mongodb.DB;importcom.mongodb.DBCollection;importcom.mongodb.BasicDBObject;importcom.mongodb.DBObject;importcom.mongodb.DBCursor;importcom.mongodb.ServerAddress;importjava.util.Arrays;publicclassMongoDBJDBC{publicstaticvoidmain(Stringargs[]){try{// 连接到 mongodb 服务MongoClientmongoClient=newMongoClient("localhost",27017);// 连接到数据库DB db=mongoClient.getDB("test");System.out.println("Connect to database successfully");booleanauth=db.authenticate(myUserName,myPassword);System.out.println("Authentication: "+auth);DBCollectioncoll=db.getCollection("mycol");System.out.println("Collection mycol selected successfully");BasicDBObjectdoc=newBasicDBObject("title","MongoDB").append("description","database").append("likes",100).append("url","http://www.w3cschool.cc/mongodb/").append("by","w3cschool.cc");coll.insert(doc);System.out.println("Document inserted successfully");}catch(Exceptione){System.err.println(e.getClass().getName()+": "+e.getMessage());}}}
编译运行以上程序,输出结果如下:
Connectto database successfullyAuthentication:trueCollectionmycol selected successfullyDocumentinserted successfully
检索所有文档
我们可以使用com.mongodb.DBCollection类中的 find() 方法来获取集合中的所有文档。
此方法返回一个游标,所以你需要遍历这个游标。
代码片段如下:
importcom.mongodb.MongoClient;importcom.mongodb.MongoException;importcom.mongodb.WriteConcern;importcom.mongodb.DB;importcom.mongodb.DBCollection;importcom.mongodb.BasicDBObject;importcom.mongodb.DBObject;importcom.mongodb.DBCursor;importcom.mongodb.ServerAddress;importjava.util.Arrays;publicclassMongoDBJDBC{publicstaticvoidmain(Stringargs[]){try{// 连接到 mongodb 服务MongoClientmongoClient=newMongoClient("localhost",27017);// 连接到数据库DB db=mongoClient.getDB("test");System.out.println("Connect to database successfully");booleanauth=db.authenticate(myUserName,myPassword);System.out.println("Authentication: "+auth);DBCollectioncoll=db.getCollection("mycol");System.out.println("Collection mycol selected successfully");DBCursorcursor=coll.find();inti=1;while(cursor.hasNext()){System.out.println("Inserted Document: "+i);System.out.println(cursor.next());i++;}}catch(Exceptione){System.err.println(e.getClass().getName()+": "+e.getMessage());}}}
编译运行以上程序,输出结果如下:
Connectto database successfullyAuthentication:trueCollectionmycol selected successfullyInsertedDocument:1{"_id":ObjectId(7df78ad8902c),"title":"MongoDB","description":"database","likes":100,"url":"http://www.w3cschool.cc/mongodb/","by":"w3cschool.cc"}
更新文档
你可以使用 com.mongodb.DBCollection 类中的 update() 方法来更新集合中的文档。
代码片段如下:
importcom.mongodb.MongoClient;importcom.mongodb.MongoException;importcom.mongodb.WriteConcern;importcom.mongodb.DB;importcom.mongodb.DBCollection;importcom.mongodb.BasicDBObject;importcom.mongodb.DBObject;importcom.mongodb.DBCursor;importcom.mongodb.ServerAddress;importjava.util.Arrays;publicclassMongoDBJDBC{publicstaticvoidmain(Stringargs[]){try{// 连接到Mongodb服务MongoClientmongoClient=newMongoClient("localhost",27017);// 连接到你的数据库DB db=mongoClient.getDB("test");System.out.println("Connect to database successfully");booleanauth=db.authenticate(myUserName,myPassword);System.out.println("Authentication: "+auth);DBCollectioncoll=db.getCollection("mycol");System.out.println("Collection mycol selected successfully");DBCursorcursor=coll.find();while(cursor.hasNext()){DBObjectupdateDocument=cursor.next();updateDocument.put("likes","200")col1.update(updateDocument);}System.out.println("Document updated successfully");cursor=coll.find();inti=1;while(cursor.hasNext()){System.out.println("Updated Document: "+i);System.out.println(cursor.next());i++;}}catch(Exceptione){System.err.println(e.getClass().getName()+": "+e.getMessage());}}}
编译运行以上程序,输出结果如下:
Connectto database successfullyAuthentication:trueCollectionmycol selected successfullyDocumentupdated successfullyUpdatedDocument:1{"_id":ObjectId(7df78ad8902c),"title":"MongoDB","description":"database","likes":200,"url":"http://www.w3cschool.cc/mongodb/","by":"w3cschool.cc"}
删除第一个文档
要删除集合中的第一个文档,首先你需要使用com.mongodb.DBCollection类中的
findOne()方法来获取第一个文档,然后使用remove 方法删除。
代码片段如下:
importcom.mongodb.MongoClient;importcom.mongodb.MongoException;importcom.mongodb.WriteConcern;importcom.mongodb.DB;importcom.mongodb.DBCollection;importcom.mongodb.BasicDBObject;importcom.mongodb.DBObject;importcom.mongodb.DBCursor;importcom.mongodb.ServerAddress;importjava.util.Arrays;publicclassMongoDBJDBC{publicstaticvoidmain(Stringargs[]){try{// 连接到Mongodb服务MongoClientmongoClient=newMongoClient("localhost",27017);// 连接到你的数据库DB db=mongoClient.getDB("test");System.out.println("Connect to database successfully");booleanauth=db.authenticate(myUserName,myPassword);System.out.println("Authentication: "+auth);DBCollectioncoll=db.getCollection("mycol");System.out.println("Collection mycol selected successfully");DBObjectmyDoc=coll.findOne();col1.remove(myDoc);DBCursorcursor=coll.find();inti=1;while(cursor.hasNext()){System.out.println("Inserted Document: "+i);System.out.println(cursor.next());i++;}System.out.println("Document deleted successfully");}catch(Exceptione){System.err.println(e.getClass().getName()+": "+e.getMessage());}}}
编译运行以上程序,输出结果如下:
Connectto database successfullyAuthentication:trueCollectionmycol selected successfullyDocumentdeleted successfully
你还可以使用 save(), limit(), skip(), sort() 等方法来操作MongoDB数据库。