searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

MongoDB使用Java进行链接,进行增删查改

2023-08-18 03:06:34
2
0

使用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();
    }
}

0条评论
0 / 1000