?Exception in thread “main“ java.lang.Error: Unresolved compilation problem错误
运行
?
public static void insert(){
try{
//连接MongoDB,指定连接数据库名,指定连接表名。
MongoCollection<Document> collection= getCollection("ku","student"); //数据库名:School 集合名:student
//实例化一个文档,文档内容为{sname:'Mary',sage:25},如果还有其他字段,可以继续追加append
Document doc1=new Document("English","45").append("Math", 89).append("Computer",100);//s=({sname:'mary',sage:25}),有几个键值对,加几个append
//实例化一个文档,文档内容为{sname:'Bob',sage:20},集合没有顺序
Document doc2=new Document("name","scofield").append("score", doc1);
List<Document> documents = new ArrayList<Document>();
//将doc1、doc2加入到documents列表中
//documents.add(doc1);
documents.add(doc2);
//将documents插入集合
collection.insertMany(documents);
System.out.println("插入成功");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
public static void find(){
try{
MongoCollection<Document> collection = getCollection("ku","student"); //数据库名:School 集合名:student
//通过游标遍历检索出的文档集合
MongoCursor<Document> cursor= collection.find(new Document("name","scofield")). projection(new Document("score",1).append("_id", 0)).iterator(); //find查询条件:sname='Mary'。projection筛选:显示sname和sage,不显示_id(_id默认会显示)
//查询所有数据
// MongoCursor<Document> cursor= collection.find().iterator();
while(cursor.hasNext()){
System.out.println(cursor.next().toJson());
}
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
??