一、MongoDB用java实现增删改查
package com.demo;
import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Updates.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.FindIterable;
import com.mongodb.MongoClient;
import com.mongodb.bulk.DeleteRequest;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Accumulators;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
public class MongoDBDemo {
static MongoCollection<Document> col;
public MongoDBDemo() {
// 连接服务器
MongoClient mongoClient = (MongoClient) new com.mongodb.MongoClient("localhost", 27017);
// 获取数据库
MongoDatabase db = mongoClient.getDatabase("test");
// 获取集合
col = db.getCollection("c1");
}
public static void main(String[] args) {
MongoDBDemo mDemo = new MongoDBDemo();
// 调用方法
// mDemo.findFilter();
mDemo.aggregate();
}
// 插入操作
public void insertOne() {
col.drop();
Document document = new Document("name","tom");
document.append("age", 18);
document.append("city", "beijing");
col.insertOne(document);
}
public void insertMany() {
col.drop();
List<Document> arrayList = new ArrayList<Document>();
for (int i = 0; i < 10; i++) {
Document document = new Document("name","tom"+i);
document.append("age", 18+i);
document.append("city", "beijing");
}
col.insertMany(arrayList);
}
// ---------------------------------删除操作
public void deleteOne() {
// 需要导入静态包
// DeleteResult result = col.deleteOne(eq("age","29"));
// 不需要静态包
Bson filter = Filters.eq("name", "tom");
DeleteResult result = col.deleteOne(filter);
System.out.println(result.toString());
}
public void deleteMany() {
// 需要导入静态包
// DeleteResult result = col.deleteOne(eq("age","29"));
// 不需要静态包
Bson filter = Filters.gt("age", 25);
DeleteResult result = col.deleteMany(filter);
// DeleteResult result = col.deleteOne(gt("age","28"));
System.out.println(result.toString());
}
// ------------------------------修改操作
public void updateOne() {
// -------------第一种方法
// UpdateResult result = col.updateOne(eq("age",25), combine(set("name", "tom000"),
// currentDate("lastModify")),new UpdateOptions().upsert(true).
验证合法性
// bypassDocumentValidation(true));
// ---------第二种方法
// 定义过滤器
Bson filter = Filters.eq("name","tom000");
// 指定修改后的文档
Document doc = new Document("$set",new Document("name","tom0")).
append("$currentDate", new Document("lastModify",true));
UpdateResult result = col.updateOne(filter, doc, new UpdateOptions().upsert(true).bypassDocumentValidation(true));
System.out.println(result.toString());
}
public void updateMany() {
UpdateResult result = col.updateMany(gt("age", 23),combine(push("score", 78)));
System.out.println(result.toString());
}
// -------------查询
public void findAll() {
// 生成文档迭代对象
FindIterable<Document> findIterable = col.find();
// 生成游标对象
MongoCursor<Document> cursor = findIterable.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
public void findFilter() {
// FindIterable<Document> findIterable = col.find(and(gt("age", 21),lt("age", 25),eq("name","tom")));
FindIterable<Document> findIterable = col.find(new Document("age",new Document("$gt",21).append("$lt", 25).append("name", "tom")));
// 生成游标对象
MongoCursor<Document> cursor = findIterable.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
public void aggregate() {
AggregateIterable<Document> aggregate = col.aggregate(Arrays.asList(Aggregates.match(gt("age", 22)),
Aggregates.group("$address.city", Accumulators.sum("count", 1))));
// 生成游标对象
MongoCursor<Document> cursor = aggregate.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
}
二、方法的封装
1.插入
代码如下(示例):
public void insert(List list) {
col.drop();
col.insertMany(list);
}
2.删除
代码如下(示例):
// ---------------------------------删除操作
public void deleteOne(Bson filter,DeleteResult result) {
result = col.deleteOne(filter);
System.out.println(result.toString());
}
public void deleteMany(Bson filter,DeleteResult result) {
result = col.deleteMany(filter);
System.out.println(result.toString());
}
3.更新
// ------------------------------修改操作
public void updateOne(Bson filter, Document doc, UpdateOptions options) {
UpdateResult result;
if (options == null) {
result=col.updateOne(filter, doc);
}else {
result = col.updateOne(filter, doc, options);
}
System.out.println(result.toString());
}
public void updateMany(Bson filter, Document doc, UpdateOptions options) {
UpdateResult result;
if (options == null) {
result=col.updateMany(filter, doc);
}else {
result = col.updateMany(filter, doc, options);
}
System.out.println(result.toString());
}
4.查询
// -------------查询
public void findAll() {
// 生成文档迭代对象
FindIterable<Document> find = col.find();
printResult(find);
}
public void findFilter(Document doc) {
FindIterable<Document> find = col.find(doc);
printResult(find);
}
}
5.遍历
public void printResult(FindIterable<Document> find) {
// 生成游标对象
MongoCursor<Document> cursor = find.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}