版本我选择的是<mongo-driver-version>3.12.10</mongo-driver-version>
<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> </dependencies>
package com.twc; import com.mongodb.MongoClient; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import org.bson.Document; import org.bson.conversions.Bson; import org.junit.Test; import java.util.Random; public class MongoJDBC { public static MongoDatabase getDataBase(String db){ MongoClient client = new MongoClient("localhost", 27017); return client.getDatabase(db); } String dbName = "mydb"; String collName = "c3"; @Test public void testCreateCollection(){ MongoDatabase dataBase = getDataBase(dbName); dataBase.createCollection(collName); } @Test public void testInsert(){ MongoDatabase dataBase = getDataBase(dbName); MongoCollection<Document> coll = dataBase.getCollection(collName); for (int i = 0; i < 100; i++) { coll.insertOne(new Document("name", "name" + new Random().nextInt(10000)) .append("age", 15 + new Random().nextInt(40)) .append("gender", new Random().nextBoolean() ? "female" : "male")); } } @Test public void testFind(){ MongoDatabase dataBase = getDataBase(dbName); MongoCollection<Document> coll = dataBase.getCollection(collName); printAll(coll); } @Test public void updateMany(){ MongoDatabase dataBase = getDataBase(dbName); MongoCollection<Document> coll = dataBase.getCollection(collName); //将18以上的标记为成年,以下的为未成年 Bson gte18 = Filters.gte("age", 18); coll.updateMany(gte18, new Document("$set", new Document("adult", true))); //将18以上的标记为成年,以下的为未成年 Bson lt18 = Filters.lt("age", 18); coll.updateMany(lt18, new Document("$set", new Document("adult", false))); printAll(coll); System.out.println("-----DeleteMany"); coll.deleteMany(Filters.eq("gender", "female")); printAll(coll); } private void printAll(MongoCollection<Document> coll) { FindIterable<Document> documents = coll.find(); for (Document document : documents) { System.out.println(document); } } }