package db;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
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;
public class MongoDB {
public static void main(String[] args) {
try {
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient("localhost", 27017);
// 连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
//创建集合member
mongoDatabase.createCollection("member");
//获取member集合
MongoCollection<Document> collection = mongoDatabase.getCollection("user");
//文档迭代器
FindIterable<Document> findIterable = collection.find();
//创建游标
MongoCursor<Document> cursor = findIterable.iterator();
while(cursor.hasNext()){
Document document = cursor.next();
System.out.println(document.toJson());
}
//插入文档
Document document = new Document();
document.append("school", "同安一中");
collection.insertOne(document);
//插入多条文档
List<Document> list = new ArrayList<>();
list.add(document);
list.add(document);
collection.insertMany(list);
//更新文档
collection.updateMany(Filters.eq("name", "xm"), new Document("$set",new Document("age",85)));
//删除多个文档
collection.deleteMany(Filters.eq("school","同安一中"));
//删除一个文档
collection.deleteOne(Filters.gt("age", 80));
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}