初学mongoDB

时间:2024-11-12 07:02:18
import com.mongodb.MongoClientSettings; import com.mongodb.client.*; import com.mongodb.client.model.Filters; import com.mongodb.client.model.Updates; import org.bson.Document; import org.bson.conversions.Bson; import java.util.Arrays; public class MongoDBExample { public static void main(String[] args) { // 创建 MongoDB 客户端 MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); // 选择数据库 MongoDatabase database = mongoClient.getDatabase("testDB"); // 选择集合 MongoCollection<Document> collection = database.getCollection("testCollection"); // 插入文档 insertDocument(collection); // 查询文档 findDocument(collection); // 更新文档 updateDocument(collection); // 删除文档 deleteDocument(collection); // 关闭 MongoDB 客户端 mongoClient.close(); } // 插入文档示例 public static void insertDocument(MongoCollection<Document> collection) { Document document = new Document("name", "Alice") .append("age", 25) .append("skills", Arrays.asList("Java", "MongoDB", "Spring")); collection.insertOne(document); System.out.println("文档插入成功: " + document.toJson()); } // 查询文档示例 public static void findDocument(MongoCollection<Document> collection) { Document document = collection.find(Filters.eq("name", "Alice")).first(); if (document != null) { System.out.println("查询结果: " + document.toJson()); } else { System.out.println("未找到符合条件的文档"); } } // 更新文档示例 public static void updateDocument(MongoCollection<Document> collection) { Bson filter = Filters.eq("name", "Alice"); Bson updateOperation = Updates.set("age", 26); collection.updateOne(filter, updateOperation); System.out.println("文档更新成功"); } // 删除文档示例 public static void deleteDocument(MongoCollection<Document> collection) { Bson filter = Filters.eq("name", "Alice"); collection.deleteOne(filter); System.out.println("文档删除成功"); } }