import com.mongodb.client.*; import com.mongodb.client.MongoClient; import com.mongodb.client.model.Filters; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.UpdateResult; import org.bson.Document; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import static com.mongodb.client.model.Accumulators.sum; import static com.mongodb.client.model.Aggregates.group; import static com.mongodb.client.model.Aggregates.match; import static com.mongodb.client.model.Aggregates.project; import static com.mongodb.client.model.Filters.and; import static com.mongodb.client.model.Filters.eq; import static com.mongodb.client.model.Filters.exists; import static com.mongodb.client.model.Filters.gt; import static com.mongodb.client.model.Filters.gte; import static com.mongodb.client.model.Filters.lt; import static com.mongodb.client.model.Filters.lte; import static com.mongodb.client.model.Projections.excludeId; import static com.mongodb.client.model.Sorts.descending; import static com.mongodb.client.model.Updates.inc; import static com.mongodb.client.model.Updates.set; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; public class MyMongodbTest { public static void main(String[] args) throws Exception{ try{ // 连接到 mongodb 服务 // MongoClient mongoClient = new MongoClient("localhost", 27017); MongoClient mongoClient = MongoClients.create(); // 连接到数据库 MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol"); System.out.println("Connect to database successfully"); //不能重复创建 // mongoDatabase.createCollection("test"); // System.out.println("集合创建成功"); MongoCollection<Document> collection = mongoDatabase.getCollection("test"); System.out.println("集合 test 选择成功"); //插入文档 /** * 1. 创建文档 org.bson.Document 参数为key-value的格式 * 2. 创建文档集合List<Document> * 3. 将文档集合插入数据库集合中 mongoCollection.insertMany(List<Document>) 插入单个文档可以用 mongoCollection.insertOne(Document) * */ Document document = new Document("title", "MongoDB001"). append("description", "database"). append("likes", 100). append("by", "Fly"); List<Document> documents = new ArrayList<Document>(); documents.add(document); collection.insertMany(documents); System.out.println("文档插入成功"); //检索所有文档 /** * 1. 获取迭代器FindIterable<Document> * 2. 获取游标MongoCursor<Document> * 3. 通过游标遍历检索出的文档集合 * */ FindIterable<Document> findIterable = collection.find(); MongoCursor<Document> mongoCursor = findIterable.iterator(); while(mongoCursor.hasNext()){ System.out.println(mongoCursor.next()); } //更新文档 将文档中likes=100的文档修改为likes=200 collection.updateMany(Filters.eq("likes", 100), new Document("$set",new Document("likes",200))); //检索查看结果 FindIterable<Document> findIterableUp = collection.find(); MongoCursor<Document> mongoCursorUp = findIterableUp.iterator(); while(mongoCursorUp.hasNext()){ System.out.println(mongoCursorUp.next()); } }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } }