实验环境:
1、Linux Ubuntu 14.04;
2、jdk-7u75-linux-x64;
3、mongodb-linux-x86_64-3.4.2;
4、eclipse-java-juno-SR2-linux-gtk-x86_64。
实验原理
Java驱动是MongoDB最早的驱动。它已经用于生产环境多年,而且非常稳定,是企业开发的首选。
要在Java应用中访问和使用MongoDB,需要使用Java MongoDB驱动程序。Java MongoDB驱动程序是一个库,它提供了多个对象,供使用者连接数据库,进而查找和操作集合中的对象,这些对象分别表示MongoDB服务器连接、数据库、集合、游标和文档,提供了在Java应用程序中集成MongoDB数据库中的数据所需的功能。
Java对象MongoClient提供了连接到MongoDB服务器和访问数据库的功能。要在应用程序中实现MongoDB,首先要创建一个MongoClient对象实例,然后就可使用它来访问数据库。
实验目的:
1、了解使用Java操作MongoDB的流程
2、学习编写Java操作MongoDB的代码
实验内容
1.编写Java代码连接MongoDB数据库。
2.编写Java代码在MongoDB中创建集合。
3.编写Java代码在MongoDB中获取集合。
4.编写Java代码在MongoDB中插入文档。
5.编写Java代码在MongoDB中检索所有文档。
6.编写Java代码在MongoDB中更新文档。
7.编写Java代码在MongoDB中删除文档。
实验步骤
连接数据库:
private static MongoClient mongoClient;
private static MongoDatabase mongoDatabase;
public static void getConn(){
mongoClient=new MongoClient("192.168.132.128",27017);
mongoDatabase=mongoClient.getDatabase("test");
System.out.println("已连接数据库");
}
创建集合:
public static void main(String[]args){
getConn();
mongoDatabase.createCollection("model");
System.out.println("Collection create successfully");
}
获取集合:
public static void main(String[]args){
getConn();
MongoCollection<Document>collection=mongoDatabase.getCollection("model");
System.out.println("Get collection model successfully");
}
插入文档:
@Test
public static void insert(){
MongoCollection<Document> collection=mongoDatabase.getCollection("model");
Document document=new Document("name","tryuser").append("score","80").append("sex","man").append("age","20");
collection.insertOne(document);
System.out.println("添加成功");
}
public static void main(String[]args){
getConn();
insert();
}
检索所有文档:
@Test
public static void findall() {
MongoCollection<Document>collection=mongoDatabase.getCollection("Student");
MongoCursor<Document>iterator=collection.find().iterator();
System.out.println("表Student的数据为");
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
public static void main(String[]args){
getConn();
findall();
}
更新文档:
@Test
public static void updatetest(){
MongoCollection<Document>collection=mongoDatabase.getCollection("model");
Bson filter= Filters.eq("name","tryuser");
Document document=new Document("$set",new Document("name","UPDATEUSER"));
collection.updateOne(filter,document);
System.out.println("更改成功");
}
public static void main(String[]args){
getConn();
updatetest();
}
删除文档:
@Test
public static void deletetest(){
MongoCollection<Document>collection=mongoDatabase.getCollection("model");
Bson filter= Filters.eq("name","UPDATEUSER");
collection.deleteOne(filter);
System.out.println("删除成功");
}
public static void main(String[]args){
getConn();
deletetest();
}
1.在Linux本地新建/data/mongodb8目录。
- mkdir -p /data/mongodb8
2.切换到/data/mongodb8目录,使用wget命令,下载http://192.168.1.100:60000/allfiles/mongodb8中的文件。
- cd /data/mongodb8
- wget http://192.168.1.100:60000/allfiles/mongodb8/mongodbjar.tar.gz
3.将/data/mongodb8目录中的mongodbjar.tar.gz解压到当前目录下。
- tar zxvf mongodbjar.tar.gz
4.启动MongoDB shell。
- numactl --interleave=all mongod -config /apps/mongodb/bin/mongodb.conf
- mongo
5.切换到admin数据库,使用root账户。
- use admin
- db.auth('root','strongs')
6.开启Eclipse,创建Java Project项目,命名为MongoJava。
7.在MongoJava项目下新建包,名为mongo。
8.在mongo包下新建类,类名为mimalianjie。
9.添加项目依赖的jar包,右键单击MongoJava,选择Import。
10.选择General中的File System,点击Next。
11.选择/data/mongodb8中的mongodbjar文件夹,并勾选Create top-level folder。
12.选中mongodbjar文件夹中全部文件,右击选择Build Path中的Add to Build Path。
13.连接数据库:编写代码,功能为连接Mongodb数据库。我们需要指定数据库名称,如果指定的数据库不存在,mongo会自动创建数据库。
完整代码为:
- package mongo;
- import java.util.ArrayList;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.MongoDatabase;
- public class mimalianjie {
- public static void main(String[] args){
- try {
- ServerAddress serverAddress = new ServerAddress("localhost",27017);
- ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();
- addrs.add(serverAddress);
- MongoCredential credential = MongoCredential.createScramSha1Credential("root", "admin", "strongs".toCharArray());
- ArrayList<MongoCredential> credentials = new ArrayList<MongoCredential>();
- credentials.add(credential);
- MongoClient mongoClient = new MongoClient(addrs,credentials);
- MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
- System.out.println("Connect to database successfully");
- } catch (Exception e) {
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- }
编译运行以上程序,输出结果如下:
14.创建集合:与上述步骤相同,在mongo包下新建类,类名为chuangjianjihe,编写代码,功能为在test库下创建集合mycol(使用com.mongodb.client.MongoDatabase类中的createCollection()来创建集合)
完整代码为:
- package mongo;
- import java.util.ArrayList;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.MongoDatabase;
- public class chuangjianjihe {
- public static void main(String[] args){
- try {
- ServerAddress serverAddress = new ServerAddress("localhost",27017);
- ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();
- addrs.add(serverAddress);
- MongoCredential credential = MongoCredential.createScramSha1Credential("root", "admin", "strongs".toCharArray());
- ArrayList<MongoCredential> credentials = new ArrayList<MongoCredential>();
- credentials.add(credential);
- MongoClient mongoClient = new MongoClient(addrs,credentials);
- MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
- System.out.println("Connect to database successfully");
- mongoDatabase.createCollection("mycol");
- System.out.println("Collection mycol was created successfully");
- } catch (Exception e) {
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- }
编译运行以上程序,输出结果如下:
15.在mongodb中进行验证:
- use test
- show collections
16.获取集合:在mongo包下新建类,名为huoqujihe,并编写代码,功能为获取所需集合(使用com.mongodb.client.MongoDatabase类的 getCollection() 方法来获取一个集合)
完整代码为:
- package mongo;
- import java.util.ArrayList;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.MongoCollection;
- import com.mongodb.client.MongoDatabase;
- public class huoqujihe {
- public static void main(String[] args){
- try {
- ServerAddress serverAddress = new ServerAddress("localhost",27017);
- ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();
- addrs.add(serverAddress);
- MongoCredential credential = MongoCredential.createScramSha1Credential("root",
- "admin", "strongs".toCharArray());
- ArrayList<MongoCredential> credentials = new ArrayList<MongoCredential>();
- credentials.add(credential);
- MongoClient mongoClient = new MongoClient(addrs,credentials);
- MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
- System.out.println("Connect to database successfully");
- MongoCollection<org.bson.Document> collection = mongoDatabase.getCollection("mycol");
- System.out.println("Collect mycol selection is successful");
- } catch (Exception e) {
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- }
编译运行以上程序,输出结果如下:
17.插入文档:在mongo包中新建类,名为charuwendang,功能为连接test库,选择mycol集合并向其中插入文档。(使用com.mongodb.client.MongoCollection类的insertMany()方法来插入一个文档)
完整代码为:
- package mongo;
- import java.util.ArrayList;
- import java.util.List;
- import org.bson.Document;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.MongoCollection;
- import com.mongodb.client.MongoDatabase;
- public class charuwendang{
- public static void main( String args[] ){
- try{
- ServerAddress serverAddress = new ServerAddress("localhost",27017);
- ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();
- addrs.add(serverAddress);
- MongoCredential credential = MongoCredential.createScramSha1Credential("root",
- "admin", "strongs".toCharArray());
- ArrayList<MongoCredential> credentials = new ArrayList<MongoCredential>();
- credentials.add(credential);
- MongoClient mongoClient = new MongoClient(addrs,credentials);
- MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
- System.out.println("Connect to database successfully");
- MongoCollection<org.bson.Document> collection = mongoDatabase.getCollection("mycol");
- System.out.println("Collection mycol selection is successful");
- Document document = new Document("name", "zhangyudashuju").
- append("description", "YXCX").
- append("likes", 100).
- append("location", "BJ");
- List<Document> documents = new ArrayList<Document>();
- documents.add(document);
- collection.insertMany(documents);
- System.out.println("Document inserted successfully");
- }catch(Exception e){
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- }
编译运行以上程序,输出结果如下:
18.在mongodb中进行查询验证:
- use test
- show collections
- db.mycol.find()
19.检索文档:在mongo包中新建类,名为jiansuosuoyouwendang,功能为检索test库下,mycol集合中的所有文档(使用 com.mongodb.client.MongoCollection 类中的 find() 方法来获取集合中的所有文档)
- package mongo;
- import java.util.ArrayList;
- import org.bson.Document;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.FindIterable;
- import com.mongodb.client.MongoCollection;
- import com.mongodb.client.MongoCursor;
- import com.mongodb.client.MongoDatabase;
- public class jiansuosuoyouwendang{
- public static void main( String args[] ){
- try{
- ServerAddress serverAddress = new ServerAddress("localhost",27017);
- ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();
- addrs.add(serverAddress);
- MongoCredential credential = MongoCredential.createScramSha1Credential("root",
- "admin", "strongs".toCharArray());
- ArrayList<MongoCredential> credentials = new ArrayList<MongoCredential>();
- credentials.add(credential);
- MongoClient mongoClient = new MongoClient(addrs,credentials);
- MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
- System.out.println("Connect to database successfully");
- MongoCollection<org.bson.Document> collection = mongoDatabase.getCollection("mycol");
- System.out.println("Collection mycol selection is successful");
- FindIterable<Document> findIterable = collection.find();
- MongoCursor<Document> mongoCursor = findIterable.iterator();
- while(mongoCursor.hasNext()){
- System.out.println(mongoCursor.next());
- }
- }catch(Exception e){
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- }
编译运行以上程序,输出结果如下:
20.更新文档:在mongo包中新建类,名为gengxinwendang,功能为选择test库下mycol集合,将文档中的likes=100改为likes=200(使用 com.mongodb.client.MongoCollection 类中的updateMany() 方法来更新集合中的文档)
完整代码为:
- package mongo;
- import java.util.ArrayList;
- import org.bson.Document;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.FindIterable;
- import com.mongodb.client.MongoCollection;
- import com.mongodb.client.MongoCursor;
- import com.mongodb.client.MongoDatabase;
- import com.mongodb.client.model.Filters;
- public class gengxinwendang{
- public static void main( String args[] ){
- try{
- ServerAddress serverAddress = new ServerAddress("localhost",27017);
- ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();
- addrs.add(serverAddress);
- MongoCredential credential = MongoCredential.createScramSha1Credential("root",
- "admin", "strongs".toCharArray());
- ArrayList<MongoCredential> credentials = new ArrayList<MongoCredential>();
- credentials.add(credential);
- MongoClient mongoClient = new MongoClient(addrs,credentials);
- MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
- System.out.println("Connect to database successfully");
- MongoCollection<org.bson.Document> collection = mongoDatabase.getCollection("mycol");
- System.out.println("Collection mycol selection is successful");
- collection.updateMany(Filters.eq("likes", 100), new Document("$set",new Document("likes",200)));
- FindIterable<Document> findIterable = collection.find();
- MongoCursor<Document> mongoCursor = findIterable.iterator();
- while(mongoCursor.hasNext()){
- System.out.println(mongoCursor.next());
- }
- }catch(Exception e){
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- }
编译运行以上程序,输出结果如下:
21.在mongodb中进行查询验证
- use test
- show collections
- db.mycol.find()
22.删除文档:在mongo包中新建类,名为sanchuwendang,功能为选择test库下mycol集合,删除所有符合条件(likes=200)的文档。(使用com.mongodb.DBCollection类中的findOne()方法来获取第一个文档,然后使用remove方法删除)
完整代码为:
- package mongo;
- import java.util.ArrayList;
- import org.bson.Document;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.FindIterable;
- import com.mongodb.client.MongoCollection;
- import com.mongodb.client.MongoCursor;
- import com.mongodb.client.MongoDatabase;
- import com.mongodb.client.model.Filters;
- public class sanchuwendang{
- public static void main( String args[] ){
- try{
- ServerAddress serverAddress = new ServerAddress("localhost",27017);
- ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();
- addrs.add(serverAddress);
- MongoCredential credential = MongoCredential.createScramSha1Credential("root",
- "admin", "strongs".toCharArray());
- ArrayList<MongoCredential> credentials = new ArrayList<MongoCredential>();
- credentials.add(credential);
- MongoClient mongoClient = new MongoClient(addrs,credentials);
- MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
- System.out.println("Connect to database successfully");
- MongoCollection<org.bson.Document> collection = mongoDatabase.getCollection("mycol");
- System.out.println("Collection mycol selection is successful");
- //删除符合条件的第一个文档
- //collection.deleteOne(Filters.eq("likes", 200));
- //删除所有符合条件的文档
- collection.deleteMany (Filters.eq("likes", 200));
- //检索查看结果
- FindIterable<Document> findIterable = collection.find();
- MongoCursor<Document> mongoCursor = findIterable.iterator();
- while(mongoCursor.hasNext()){
- System.out.println(mongoCursor.next());
- }
- }catch(Exception e){
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- }
编译运行以上程序,输出结果如下:
23.在mongodb中进行查询验证
- use test
- show collections
- db.mycol.find()
查询结果为空,证明文档已被删除。