1,连接mongo
import java.util.ArrayList;
import java.util.List;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
/**
* mongodb 连接工具类
*/
public class MongoDBUtil {
/**
* 不通过认证获取连接数据库对象
* @return
*/
public static MongoDatabase getConnect(){
//连接到 mongodb 服务
MongoClient mongoClient = new MongoClient("服务器地址", 27017);
//连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("mongo库名");
//返回连接数据库对象
return mongoDatabase;
}
/**
* 需要密码认证方式连接
* @return
*/
public static MongoDatabase getConnect2(){
List<ServerAddress> adds = new ArrayList<ServerAddress>();
//ServerAddress()两个参数分别为 服务器地址 和 端口
ServerAddress serverAddress = new ServerAddress("服务器地址", 27017);
adds.add(serverAddress);
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
//MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("用户名", "mongo库名", "密码".toCharArray());
credentials.add(mongoCredential);
//通过连接认证获取MongoDB连接
MongoClient mongoClient = new MongoClient(adds, credentials);
//连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("mongo库名");
//返回连接数据库对象
return mongoDatabase;
}
}
2,其他包地址
import com.mongodb.client.MongoCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
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;
import com.mongodb.client.result.DeleteResult;
import org.bson.Document;
import org.bson.conversions.Bson;
3,查询
//连接到 mongodb 服务
MongoDatabase mongoDatabase = MongoDBUtil.getConnect2();
//获取集合
MongoCollection<Document> collection = mongoDatabase.getCollection("集合名");
//多查询条件
Bson filter = Filters.and(Filters.eq("字段名", "值"),Filters.eq("字段名2", "值2"));
//排序
Bson sort = Filters.eq("visitDate",-1);
//指定查询过滤器查询
FindIterable findIterable1 = collection.find(filter).sort(sort);
MongoCursor<Document> cursor1 = findIterable1.iterator();
//遍历处理数据
if(cursor1 != null && cursor1.hasNext()) {
}
4,增加
List<Document> recordVos = new ArrayList<Document>();
//集合可循环加入 recordVos
String json = JSON.toJSONString(你的实体类);
Document document = Document.parse(json);
recordVos.add(document);
//保存到mongo
collection.insertMany(recordVos);
5,删除
Bson filter_del = Filters.eq("字段名", "值");
//删除
DeleteResult dResult = collection.deleteMany(filter_del);
6,jar包 地址
- 也可去以下网址下载或获取maven地址
https://www.mvnjar.com/search/mongodb-driver.html