下载mongo-java-driver-3.8.2.jar包,将jar包build path到java项目。
mongo-java-driver-3.8.2.jar下载地址
jar包版本为3.8.2
一、基础操作:
一、连接数据库
1:无密码连接
//连接MongoDB服务,本机是localhost,远程连接改成其IP地址,27017是端口号
MongoClient mongoClient = new MongoClient("localhost", 27017);
//连接数据库,databaseName是数据库名,若数据库不存在会自动创建
MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
//获取集合,集和名collectionName
MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collectionName");
2:有密码连接
//addrs数组存储MongoDB服务器,192.145.147.2是远程连接ip地址,localhost表示本机
ServerAddress serverAddress = new ServerAddress("192.145.147.2",27017);
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
//credentials存储登录数据库管理,用户名root,数据库名admin,密码root
MongoCredential credential = MongoCredential.createScramSha1Credential("root","admin","root".toCharArray());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
//登录MongoDB服务器
MongoClient mongoClient = new MongoClient(addrs,credentials);
//连接MongoDB数据库databaseName
MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
//获取集合,集和名collectionName
MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collectionName");
二、插入数据文档
1、:document文档插入
//document文档
Document document = new Document("title", “MongoDB”).append("description","mongoDB").append("number",100).append("location","here");
List<Document> documents = new ArrayList<Document>();
documents.add(document);
mongoCollection.insertMany(documents); //添加文档(对应的BSON数据)
2:
DBObject aplatform = new BasicDBObject();
aplatform.put("platformName", "MongoDB");
aplatform.put("platformId","123");
mongoCollection.insertOne(aplatform);
3:map容器
Map<String,Object> map = new HashMap<String,Object>();
map.put("platformName", "MongoDB");
map.put("platformId","123");
DBObject aplatform = new BasicDBObject(map);
mongoCollection.insertOne(aplatform);
三、查询
1:
FindIterable<Document> findIterable = mongoCollection.find();//获取迭代器
MongoCursor<Document> mongoCursor = findIterable.iterator();//获取游标
//循环输出数据
while(mongoCursor.hasNext()) {
Document cursor = mongoCursor.next(); //cursor值为当前循环内的document
System.out.println(cursor.getString("platformName"));//输出本次循环document的platformName属性的值
System.out.println(cursor);//输出本次循环文档所有内容
}
2:条件查询
DBObject aplatform = new BasicDBObject();
aplatform.put("platformName", "MongoDB");
FindIterable<Document> findIterable = mongoCollection.find(aplatform);//获取迭代器
MongoCursor<Document> mongoCursor = findIterable.iterator();//获取游标
while(mongoCursor.hasNext()) {
System.out.println(mongoCursor.next());//输出本次循环文档所有内容
}
3:
DBObject aplatform = new BasicDBObject("platformId",new BasicDBObject("$gte",5));
FindIterable<Document> findIterable = mongoCollection.find(aplatform);//获取迭代器
MongoCursor<Document> mongoCursor = findIterable.iterator();//获取游标
while(mongoCursor.hasNext()) {
System.out.println(mongoCursor.next());//输出本次循环文档所有内容
}
//$gte(>) $lte(<) $ne(<>) $in $nin $all $exists $or $nor $where $type
四、更新
mongoCollection.updateMany(Filters.eq("number", 100), new Document("$set",new Document("number",200))); //更新文档 将文档中number=100的文档修改为number=200
五、删除
mongoCollection.deleteOne(Filters.eq("platformName", "MongDB")); //删除符合条件的第一个文档
mongoCollection.deleteMany (Filters.eq("platformName", "MongDB")); //删除所有符合条件的文档
PS:更多基本操作
二、基础示例:
1、没有密码登录
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
public class App {
public static void main(String args[]) {
try {
// 连接MongoDB服务器,本机是localhost,远程连接改成IP地址
MongoClient mongoClient = new MongoClient("localhost", 27017);
// 连接数据库“databaseName”,如果没有databaseName,MongoDB会自动创建
MongoDatabase mgdb = mongoClient.getDatabase("databaseName");
System.out.println("Connect to database successfully!");
System.out.println("MongoDatabase inof is : "+mgdb.getName());
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
2、有密码登录
import java.util.ArrayList;
import java.util.List;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;
public class mongo {
public static void main(String[]args) {
try {
//addrs数组存储MongoDB服务器,192.145.147.2是远程连接ip地址,localhost表示本机
ServerAddress serverAddress = new ServerAddress("192.145.147.2",27017);
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
//credentials存储登录数据库管理,用户名root,数据库名admin,密码root
MongoCredential credential = MongoCredential.createScramSha1Credential("root","admin","root".toCharArray());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
//登录MongoDB服务器
MongoClient mongoClient = new MongoClient(addrs,credentials);
//连接MongoDB数据库databaseName
MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
System.out.println("Connect to database successfully!");
}catch(Exception e) {
System.err.println(e.getClass().getName()+":"+e.getMessage());
}
}
}
3、创建集合(无密码登录、有密码登录都可用)
package mongodb;
import java.util.ArrayList;
import java.util.List;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;
public class mongo {
public static void main(String[]args) {
try {
//登录MongoDB服务器
MongoClient mongoClient = new MongoClient("server1", 27017);
//连接MongoDB数据库databaseName
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
System.out.println("Connect to database successfully!");
mongoDatabase.createCollection("mycol");
System.out.println("集合创建成功");
}catch(Exception e) {
System.err.println(e.getClass().getName()+":"+e.getMessage());
}
}
}
4、获取集合
package mongodb;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class mongo {
public static void main(String[]args) {
try {
//addrs数组存储MongoDB服务器,
ServerAddress serverAddress = new ServerAddress("server1",27017);
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
//credentials存储登录数据库管理,用户名root,主数据库admin,密码root
MongoCredential credential = MongoCredential.createScramSha1Credential("root","admin","root".toCharArray());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
//登录MongoDB服务器
MongoClient mongoClient = new MongoClient(addrs,credentials);
//连接MongoDB数据库databaseName
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
System.out.println("Connect to database successfully!");
MongoCollection<Document> collection = mongoDatabase.getCollection("mycol");
System.out.println("集合 mycol 选择成功");
}catch(Exception e) {
System.err.println(e.getClass().getName()+":"+e.getMessage());
}
}
}
5、插入文档(BSON格式)
package mongodb;
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 mongo {
public static void main(String[]args) {
try {
ServerAddress serverAddress = new ServerAddress("server1",27017);
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("root", "admin","root".toCharArray());
List<MongoCredential> mongoCredentials = new ArrayList<MongoCredential>();
mongoCredentials.add(mongoCredential);
//登录MongoDB服务器
MongoClient mongoClient = new MongoClient(addrs, mongoCredentials);
//连接MongoDB数据库databaseName
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
System.out.println("Connect to database successfully!");
MongoCollection<Document> collection = mongoDatabase.getCollection("mycol");
System.out.println("集合 mycol 选择成功");
Document document = new Document("title", "MongoDB").append("descripsion", "very good").append("likes", 100).append("location", "Server1");
List<Document> documents = new ArrayList<Document>();
documents.add(document);
collection.insertMany(documents);//插入文档(BSON格式)
System.out.println("插入文档成功");
}catch(Exception e) {
System.err.println(e.getClass().getName()+":"+e.getMessage());
}
}
}
6、检索文档,查找数据
package mongodb;
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.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class mongo {
public static void main(String[]args) {
try {
ServerAddress serverAddress = new ServerAddress("server1",27017);
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("root", "admin", "root".toCharArray());
List<MongoCredential> mongoCredentials = new ArrayList<MongoCredential>();
mongoCredentials.add(mongoCredential);
//登录MongoDB服务器
MongoClient mongoClient = new MongoClient(addrs, mongoCredentials);
//连接MongoDB数据库databaseName
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
System.out.println("Connect to database successfully!");
MongoCollection<Document> collection = mongoDatabase.getCollection("mycol");
System.out.println("集合 mycol 选择成功");
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());
}
}
}
7、更新文档数据
package mongodb;
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.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
public class mongo {
public static void main(String[]args) {
try {
ServerAddress serverAddress = new ServerAddress("server1",27017);
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("root", "admin", "root".toCharArray());
List<MongoCredential> mongoCredentials = new ArrayList<MongoCredential>();
mongoCredentials.add(mongoCredential);
//登录MongoDB服务器
MongoClient mongoClient = new MongoClient(addrs, mongoCredentials);
//连接MongoDB数据库databaseName
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
System.out.println("Connect to database successfully!");
MongoCollection<Document> collection = mongoDatabase.getCollection("mycol");
System.out.println("集合 mycol 选择成功");
collection.updateMany(Filters.eq("likes", 100),new Document("$set", new Document("likes", 200)));//将文档中的likes:100更新成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());
}
}
}
8、删除文档
package mongodb;
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.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
public class mongo {
public static void main(String[]args) {
try {
ServerAddress serverAddress = new ServerAddress("server1",27017);
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("root", "admin", "root".toCharArray());
List<MongoCredential> mongoCredentials = new ArrayList<MongoCredential>();
mongoCredentials.add(mongoCredential);
//登录MongoDB服务器
MongoClient mongoClient = new MongoClient(addrs, mongoCredentials);
//连接MongoDB数据库databaseName
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
System.out.println("Connect to database successfully!");
MongoCollection<Document> collection = mongoDatabase.getCollection("mycol");
System.out.println("集合 mycol 选择成功");
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());
}
}
}