使用的時候是3.0版本的驅動java
https://www.mongodb.org/mongodb
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.2.2</version> </dependency>
MongoClient mongoClient = new MongoClient(); // 數據庫 MongoDatabase db = mongoClient.getDatabase("dbname"); // 集合 MongoCollection<Document> coll = db.getCollection("colname"); // 刪除集合 coll.drop(); // 添加索引 List<IndexModel> indexes = new ArrayList<>() indexes.add(new IndexModel(new Document("owner", 1))); coll.createIndexes(indexes); // 保存多個數據 List<Document> docs = new ArrayList<Document>(); Document doc = new Document("name", "test") .append("mail", "test@163.com"); docs.add(doc); coll.insertMany(docs); // 查詢 // 使用eq須要導入import static com.mongodb.client.model.Filters.*; FindIterable<Document> iterable = coll.find(eq("owner", owner)); // 查詢所有 FindIterable<Document> iterable = coll.find(); iterable.forEach(new Block<Document>() { @Override public void apply(final Document doc) { String name = doc.getString("name"); } }); // 刪除多個記錄 coll.deleteMany(new Document("name", "test"));