使用java 连接MongoDB数据库进行,增删查改操作,给出下面示例
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class CRUDExample {
public static void main(String[] args) {
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("mycollection");
// 插入文档
Document document = new Document("name", "John")
.append("age", 30)
.append("city", "New York");
collection.insertOne(document);
System.out.println("Document inserted");
// 查询文档
Document query = new Document("name", "John");
Document result = collection.find(query).first();
System.out.println("Query result: " + result);
// 更新文档
Document update = new Document("$set", new Document("age", 31));
collection.updateOne(query, update);
System.out.println("Document updated");
// 删除文档
collection.deleteOne(query);
System.out.println("Document deleted");
mongoClient.close();
}
}