补全代码public class Mongoconnect{ public static void main( String args[ ){ try{ MongoClient mongoClient = new_ (1)_ ; MongoDatabase mongoDatabase = mongoClient.getDatabase("mydb1"); mongoDatabase.drop0; mongoDatabase.createCollection("test1"); MongoC ollection<Document> collection =_ _(2)_ ; Document document1 = new Document); document1.append("_ id", "1"); (3)___ ; document1.append("sex", "man"); (4)_ ; List<Document> documents = new ArrayList <Document>0; documents.add(document1); collection.insertMany( (5)_ ); Findlterable <Document> iter =_ (6)_; iter.forEach(new Consumer <Document>0 { @Override public void accept(Document document) { System.out.printIn(document.toJson0); }); Document doc =_ (7)_ ; collection._ (8)_ ; }catch (Exception e) { System.er.println( e.getClass0.getName0 + ": " + e.getMessage0 ); }
时间: 2024-04-01 10:32:57 浏览: 61
public class Mongoconnect{
public static void main(String args[]) {
try{
MongoClient mongoClient = new MongoClient(); // (1) 创建MongoDB客户端
MongoDatabase mongoDatabase = mongoClient.getDatabase("mydb1");
mongoDatabase.drop();
mongoDatabase.createCollection("test1");
MongoCollection<Document> collection = mongoDatabase.getCollection("test1"); // (2) 获取集合
Document document1 = new Document();
document1.append("_id", "1"); // (3) 添加字段
document1.append("name", "John");
document1.append("sex", "man"); // (4) 添加字段
List<Document> documents = new ArrayList<Document>();
documents.add(document1);
collection.insertMany(documents); // (5) 插入文档
FindIterable<Document> iter = collection.find(); // (6) 查询集合中所有文档
iter.forEach(new Consumer<Document>() {
@Override
public void accept(Document document) {
System.out.println(document.toJson());
}
});
Document doc = collection.find(eq("_id", "1")).first(); // (7) 查询指定文档
collection.deleteMany(eq("_id", "1")); // (8) 删除文档
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
阅读全文