MongoDB (一) Java使用MongoDB[CURD]
0.引入jar包获取
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.13</version>
</dependency>
</dependencies>
1.创建连接
1.1.无密码连接
1.1.1.使用com.mongodb.MongoClient
import java.util.function.Consumer;
import org.bson.Document;
import com.mongodb.MongoClient;
public class MongoDBTest {
private final static String IP = "localhost";
private final static int PORT = 27017;
public static void main(String[] args) {
try {
MongoClient mongoClient = new MongoClient();
// 或者
MongoClient mongoClient = new MongoClient(IP, PORT);
}
}
}
1.1.2.使用com.mongodb.MongoClient
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
public class MongoDBClientTest {
public static void main(String[] args) {
try {
//本地
MongoClient mongoClient = MongoClients.create();
// 或者
MongoClient mongoClient = MongoClients.create("mongodb://localhost");
// 或者
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
// 或者
MongoClient mongoClient = MongoClients.create(new ConnectionString("mongodb://localhost"));
// 或者
MongoClient mongoClient = MongoClients.create(new ConnectionString("mongodb://localhost:27017"));
}
}
}
1.2.有密码连接
后续更新
2.创建DB
import java.util.function.Consumer;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
public class MongoDBTest {
private final static String IP = "localhost";
private final static int PORT = 27017;
private final static String DATABASE = "database";
public static void main(String[] args) {
try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
MongoDatabase db = mongoClient.getDatabase(DATABASE);
}
}
}
说明: mongodb没有创建数据库的方法, 可以通过getDatabase方法来实现, 如果该数据库存在,则不会创建新的数据库, 如果不存在, 则会自动创建.
2.集合
2.1.创建集合
import java.util.function.Consumer;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoDBTest {
private final static String IP = "localhost";
private final static int PORT = 27017;
private final static String DATABASE = "database";
private final static String COLLECTION = "reel";
public static void main(String[] args) {
try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
MongoDatabase db = mongoClient.getDatabase(DATABASE);
db.createCollection(COLLECTION);
}
}
}
2.2.获取集合
import java.util.function.Consumer;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoDBTest {
private final static String IP = "localhost";
private final static int PORT = 27017;
private final static String DATABASE = "database";
private final static String COLLECTION = "reel";
public static void main(String[] args) {
try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
MongoDatabase db = mongoClient.getDatabase(DATABASE);
MongoCollection<Document> collection = db.getCollection(COLLECTION);
// 获取集合列表
MongoIterable<String> listCollectionNames = db.listCollectionNames();
}
}
}
2.3.删除集合
import java.util.function.Consumer;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoDBTest {
private final static String IP = "localhost";
private final static int PORT = 27017;
private final static String DATABASE = "database";
private final static String COLLECTION = "reel";
public static void main(String[] args) {
try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
MongoDatabase db = mongoClient.getDatabase(DATABASE);
MongoCollection<Document> collection = db.getCollection(COLLECTION);
collection.drop();
}
}
}
3.新增
3.1.单个新增
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoDBInsertTest {
private final static String IP = "localhost";
private final static int PORT = 27017;
private final static String DATABASE = "database";
private final static String COLLECTION = "reel";
public static void main(String[] args) {
try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
insertOneData(mongoClient);
}
}
public static void insertOneData(MongoClient mongoClient) {
MongoCollection<Document> collection = getCollection(mongoClient);
Document document = new Document().append("reel_id", "X0003").append("name", "B_3").append("qty", 120);
//Document document = new Document().append("_id", 1).append("reel_id", "X0003").append("name", "B_3").append("QTY", 120);
collection.insertOne(document);
}
private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
MongoDatabase db = mongoClient.getDatabase(DATABASE);
MongoCollection<Document> collection = db.getCollection(COLLECTION);
return collection;
}
}
说明:
没有设置ID, 则数据库会自动生成一个唯一ID;
设置了ID, 如果数据库没有该ID, 则为新增操作, 如果有该ID, 则抛出异常
3.2.多个新增
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoDBInsertTest {
private final static String IP = "localhost";
private final static int PORT = 27017;
private final static String DATABASE = "database";
private final static String COLLECTION = "reel";
public static void main(String[] args) {
try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
insertManyData(mongoClient);
}
}
public static void insertManyData(MongoClient mongoClient) {
MongoCollection<Document> collection = getCollection(mongoClient);
List<Document> documents = new ArrayList<Document>();
int begin = 4;
for (int i = begin; i < begin + 3; i++) {
Document document = new Document().append("reel_id", "X000" + i).append("name", "B_" + i).append("QTY", 120 + i * 10);
documents.add(document);
}
collection.insertMany(documents);
}
private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
MongoDatabase db = mongoClient.getDatabase(DATABASE);
MongoCollection<Document> collection = db.getCollection(COLLECTION);
return collection;
}
}
4.查询
4.1.基本查询
import java.util.function.Consumer;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoDBQueryTest {
private final static String IP = "localhost";
private final static int PORT = 27017;
private final static String DATABASE = "database";
private final static String COLLECTION = "reel";
public static void main(String[] args) {
try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
basicQuery(mongoClient);
}
}
public static void basicQuery(MongoClient mongoClient) {
MongoCollection<Document> collection = getCollection(mongoClient);
FindIterable<Document> findIterable = collection.find();
findIterable.forEach(new Consumer<Document>() {
@Override
public void accept(Document document) {
String name = document.getString("name");
System.out.println(name);
}
});
}
private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
MongoDatabase db = mongoClient.getDatabase(DATABASE);
MongoCollection<Document> collection = db.getCollection(COLLECTION);
return collection;
}
}
4.2.表达式查询
4.2.1.使用Bson设置查询条件
可以使用com.mongodb.BasicDBObject
类, 或者org.bson.Document
类, 因为他们都实现 org.bson.conversions.Bson
类
import java.util.function.Consumer;
import java.util.regex.Pattern;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoDBQueryTest {
private final static String IP = "localhost";
private final static int PORT = 27017;
private final static String DATABASE = "database";
private final static String COLLECTION = "reel";
public static void main(String[] args) {
try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
regexQuery(mongoClient);
}
}
public static void regexQuery(MongoClient mongoClient) {
MongoCollection<Document> collection = getCollection(mongoClient);
BasicDBObject regexQuery = new BasicDBObject();
// $regex类似于like查询
regexQuery.put("name", new BasicDBObject("$regex", "R.*"));
// 其中的R.*也可以使用java.util.regex.Pattern替换, 如下:
// Pattern compile = Pattern.compile("^R");
// regexQuery.put("name", new BasicDBObject("$regex", compile));
// $lte $lt $qt $qte等比较运算符
regexQuery.put("qty", new BasicDBObject("$lte", 100));
// 也可以使用Document替换BasicDBObject
/**
Document regexQuery = new Document();
regexQuery.put("name", new Document("$regex", "R.*"));
*/
FindIterable<Document> findIterable = collection.find(regexQuery);
findIterable.forEach(new Consumer<Document>() {
@Override
public void accept(Document document) {
String name = document.getString("name");
System.out.println(name);
}
});
}
private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
MongoDatabase db = mongoClient.getDatabase(DATABASE);
MongoCollection<Document> collection = db.getCollection(COLLECTION);
return collection;
}
}
4.2.2.使用Filter设置查询条件
import java.util.function.Consumer;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
public class MongoDBQueryTest {
private final static String IP = "localhost";
private final static int PORT = 27017;
private final static String DATABASE = "database";
private final static String COLLECTION = "reel";
public static void main(String[] args) {
try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
filterQuery(mongoClient);
}
}
public static void filterQuery(MongoClient mongoClient) {
MongoCollection<Document> collection = getCollection(mongoClient);
Bson lt = Filters.lte("qty", 100);
FindIterable<Document> findIterable = collection.find(lt);
findIterable.forEach(new Consumer<Document>() {
@Override
public void accept(Document document) {
String name = document.getString("name");
Integer qty = document.getInteger("qty");
System.out.println(name + "->" + qty);
}
});
}
private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
MongoDatabase db = mongoClient.getDatabase(DATABASE);
MongoCollection<Document> collection = db.getCollection(COLLECTION);
return collection;
}
}
结果:
R_1->100
A_2->50
4.3.排序查询
import java.util.function.Consumer;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoDBQueryTest {
private final static String IP = "localhost";
private final static int PORT = 27017;
private final static String DATABASE = "database";
private final static String COLLECTION = "reel";
public static void main(String[] args) {
try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
sortQuery(mongoClient);
}
}
public static void sortQuery(MongoClient mongoClient) {
MongoCollection<Document> collection = getCollection(mongoClient);
FindIterable<Document> findIterable = collection.find().sort(new BasicDBObject().append("qty", 1).append("name", -1));
findIterable.forEach(new Consumer<Document>() {
@Override
public void accept(Document document) {
String name = document.getString("name");
System.out.println(name);
}
});
}
private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
MongoDatabase db = mongoClient.getDatabase(DATABASE);
MongoCollection<Document> collection = db.getCollection(COLLECTION);
return collection;
}
}
说明: sort方法第一个参数为字段名, 第二个参数 -1是倒序查询, 1是顺序查询
4.4.分页查询
import java.util.function.Consumer;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoDBQueryTest {
private final static String IP = "localhost";
private final static int PORT = 27017;
private final static String DATABASE = "database";
private final static String COLLECTION = "reel";
public static void main(String[] args) {
try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
pagingQuery(mongoClient);
}
}
public static void pagingQuery(MongoClient mongoClient) {
MongoCollection<Document> collection = getCollection(mongoClient);
FindIterable<Document> findIterable = collection.find().limit(10).skip(0);
findIterable.forEach(new Consumer<Document>() {
@Override
public void accept(Document document) {
String name = document.getString("name");
System.out.println(name);
}
});
}
private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
MongoDatabase db = mongoClient.getDatabase(DATABASE);
MongoCollection<Document> collection = db.getCollection(COLLECTION);
return collection;
}
}
说明: limit为查询的数量, skip为跳过的数量, 如果是0, 则查询的时候是从第1个数开始.
4.5.设置查询返回字段
import java.util.function.Consumer;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Projections;
public class MongoDBQueryTest {
private final static String IP = "localhost";
private final static int PORT = 27017;
private final static String DATABASE = "database";
private final static String COLLECTION = "reel";
public static void main(String[] args) {
try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
setReturnFiledQuery(mongoClient);
}
}
public static void setReturnFiledQuery(MongoClient mongoClient) {
MongoCollection<Document> collection = getCollection(mongoClient);
// 设置包含字段返回
Bson include = Projections.include("name", "qty");
// 去除部分字段返回
Bson exclude = Projections.exclude("_id");
// 也可以使用excludeId方法代替exclude("_id")
//Bson excludeId = Projections.excludeId();
//include 和 exclude可以只设置一种
Bson projection = Projections.fields(include, exclude);
FindIterable<Document> findIterable = collection.find().projection(projection);
findIterable.forEach(new Consumer<Document>() {
@Override
public void accept(Document document) {
System.out.println(document);
}
});
}
private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
MongoDatabase db = mongoClient.getDatabase(DATABASE);
MongoCollection<Document> collection = db.getCollection(COLLECTION);
return collection;
}
}
结果如下:
Document{{name=R_1, qty=100}}
Document{{name=A_2, qty=50}}
5.修改
5.1.单个修改
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.UpdateResult;
public class MongoDBUpdateTest {
private final static String IP = "localhost";
private final static int PORT = 27017;
private final static String DATABASE = "database";
private final static String COLLECTION = "reel";
public static void main(String[] args) {
try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
updateOne(mongoClient);
}
}
public static void updateOne(MongoClient mongoClient) {
MongoCollection<Document> collection = getCollection(mongoClient);
// 1.filter部分
Bson filters = Filters.lt("qty", 100);
// 或者使用BasicDBObject
//BasicDBObject filters = new BasicDBObject().append("qty", new BasicDBObject("$lt", 100));
// 2.update部分
Document document = new Document().append("$set", new Document().append("qty", 30));
// 或者使用BasicDBObject也可以
//BasicDBObject document = new BasicDBObject().append("$set", new Document().append("qty", 40));
// 或者使用Updates.combine方法也可以
// Bson updateDoc = Updates.combine(Updates.set("qty", 60));
// 3.update db
UpdateResult updateResult = collection.updateOne(filters, document);
// 还可以配置: 如果不存在该数据, 则新增一条数据
//UpdateOptions options = new UpdateOptions().upsert(true);
//UpdateResult updateResult = collection.updateMany(filter, updateDoc, options);
System.out.println(updateResult);
}
private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
MongoDatabase db = mongoClient.getDatabase(DATABASE);
MongoCollection<Document> collection = db.getCollection(COLLECTION);
return collection;
}
}
5.2.多个修改
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.UpdateResult;
public class MongoDBUpdateTest {
private final static String IP = "localhost";
private final static int PORT = 27017;
private final static String DATABASE = "database";
private final static String COLLECTION = "reel";
public static void main(String[] args) {
try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
updateMany(mongoClient);
}
}
public static void updateMany(MongoClient mongoClient) {
MongoCollection<Document> collection = getCollection(mongoClient);
Bson filter = Filters.lt("qty", 100);
Bson updateDoc = Updates.combine(Updates.set("qty", 60));
UpdateResult updateResult = collection.updateMany(filter, updateDoc);
System.out.println(updateResult);
}
private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
MongoDatabase db = mongoClient.getDatabase(DATABASE);
MongoCollection<Document> collection = db.getCollection(COLLECTION);
return collection;
}
}
5.3.替换(慎用)
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.UpdateResult;
public class MongoDBUpdateTest {
private final static String IP = "localhost";
private final static int PORT = 27017;
private final static String DATABASE = "database";
private final static String COLLECTION = "reel";
public static void main(String[] args) {
try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
replaceOne(mongoClient);
}
}
public static void replaceOne(MongoClient mongoClient) {
MongoCollection<Document> collection = getCollection(mongoClient);
Bson filter = Filters.lt("qty", 100);
Document updateDoc = new Document()
.append("qty", 20);
UpdateResult updateResult = collection.replaceOne(filter, updateDoc);
System.out.println(updateResult);
}
private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
MongoDatabase db = mongoClient.getDatabase(DATABASE);
MongoCollection<Document> collection = db.getCollection(COLLECTION);
return collection;
}
}
说明: 该方法慎用, 使用该方法替换之后, 只有设置的字段会被修改替换, 其他的字段等同于被删除, 仅剩下_id和设置的字段.
6.删除
6.1.删除单个
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
public class MongoDBDeleteTest {
private final static String IP = "localhost";
private final static int PORT = 27017;
private final static String DATABASE = "database";
private final static String COLLECTION = "reel";
public static void main(String[] args) {
try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
deleteOne(mongoClient);
}
}
public static void deleteOne(MongoClient mongoClient) {
MongoCollection<Document> collection = getCollection(mongoClient);
Bson filter = Filters.lte("qty", 20);
DeleteResult deleteResult = collection.deleteOne(filter);
System.out.println(deleteResult);
}
private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
MongoDatabase db = mongoClient.getDatabase(DATABASE);
MongoCollection<Document> collection = db.getCollection(COLLECTION);
return collection;
}
}
结果
AcknowledgedDeleteResult{deletedCount=1}
6.2.删除多个
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
public class MongoDBDeleteTest {
private final static String IP = "localhost";
private final static int PORT = 27017;
private final static String DATABASE = "database";
private final static String COLLECTION = "reel";
public static void main(String[] args) {
try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
deleteMany(mongoClient);
}
}
public static void deleteMany(MongoClient mongoClient) {
MongoCollection<Document> collection = getCollection(mongoClient);
Bson filter = Filters.lt("qty", 100);
DeleteResult deleteResult = collection.deleteMany(filter);
System.out.println(deleteResult);
}
private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
MongoDatabase db = mongoClient.getDatabase(DATABASE);
MongoCollection<Document> collection = db.getCollection(COLLECTION);
return collection;
}
}
结果
AcknowledgedDeleteResult{deletedCount=2}