前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java Python访问MongoDB

Java Python访问MongoDB

作者头像
顾翔
发布2024-09-10 16:21:01
890
发布2024-09-10 16:21:01
举报
文章被收录于专栏:啄木鸟软件测试

1.Java访问MongoDB

pom.xml

代码语言:javascript
复制
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>mongoDB</groupId>
  <artifactId>mongoDB</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
<maven-compiler-plugin-version>3.8.1</maven-compiler-plugin-version>
  </properties>
  
<dependencies>
<dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongo-java-driver</artifactId>
      <version>3.12.10</version>
</dependency>
</dependencies>
</project>

Java程序

代码语言:javascript
复制
package mongoDB;
           
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import org.bson.Document;
           
public class MongoDB {
    // MongoDB服务器的连接URI
    public static  String uri = "mongodb://192.168.31.184:27017";
    // 创建MongoClient实例
    public static MongoClientURI clientURI = new MongoClientURI(uri);    
    public MongoClient mongoClient = new MongoClient(clientURI);     
       
    public MongoDatabase connect(String dbname) {
        // 连接成功,可以进行数据库操作
        System.out.println("Connected to MongoDB");
        // 获取数据库实例
        MongoDatabase database = mongoClient.getDatabase(dbname);
        return database;
    }
    
    public void disconnect() {
           // 关闭连接
           this.mongoClient.close();
    }
    
    public MongoCollectiongetCollection(MongoDatabase database,String mycollection) {    
    
        // 获取集合实例
        MongoCollection collection = database.getCollection(mycollection);
        return collection;    
    }
    
    public void insertDocument(String key,String value,MongoCollectioncollection) {
            // 插入文档
        Document document = new Document(key, value)
               .append("age", 40);
               collection.insertOne(document);
    }
    
    public void searchDocument(String key,String value,MongoCollectioncollection) {
    // 查询文档
    Document query = new Document(key, value);
    MongoCursor cursor = collection.find(query).iterator();
    while (cursor.hasNext()) {
           Document result = cursor.next();
           System.out.println(result.toJson());
    }
}
        
    public void ViewAllDocument(MongoCollectioncollection) {
           FindIterable iterable = collection.find();
           for (Document document : iterable) {
                  System.out.println(document.toJson());
           }
    }
    
    public void updateDocument(String key_filter,String value_filter,String key_update,String value_update,MongoCollectioncollection) {
            // 更新文档
        Document filter = new Document(key_filter,value_filter);
        Document update = new Document("$set", new Document(key_update,value_update));
        collection.updateOne(filter, update);
    }
    
    public void updateDocument(String key_filter,String value_filter,String key_update,int value_update,MongoCollectioncollection) {
           // 更新文档    
       Document filter = new Document(key_filter,value_filter);
       Document update = new Document("$set", new Document(key_update,value_update));
       collection.updateOne(filter, update);
   }
    
    
    public void deleteDocument(String key,String value,MongoCollectioncollection) {
        // 删除文档
           Document filter = new Document(key, value);
           collection.deleteOne(filter);
    }
    
    public static void main(String[] args) {
           MongoDB mdb = new MongoDB();
           MongoDatabase database = mdb.connect("admin");
           MongoCollection collection = mdb.getCollection(database,"person");
           System.out.println("显示全部");
           mdb.ViewAllDocument(collection);
           System.out.println("显示一条");    
           mdb.searchDocument("name","Jerry",collection);
           mdb.insertDocument("name","Jhon",collection);
           System.out.println("插入一条Jhon");
           mdb.ViewAllDocument(collection);
           mdb.updateDocument("name","Jhon","age",19,collection);
           System.out.println("修改Jhon,修改年龄为19");
           mdb.ViewAllDocument(collection);
           mdb.deleteDocument("name","Jhon",collection);
           System.out.println("删除一条Jhon");
           mdb.ViewAllDocument(collection);
     mdb.disconnect();
    }
}

输出

代码语言:javascript
复制
{"_id": {"$oid": "66d7de35f5f38e175c5e739c"}, "name": "Jerry", "age": 28}
{"_id": {"$oid": "66d7decaf5f38e175c5e739d"}, "name": "Tom", "age": 37}
{"_id": {"$oid": "66d7df39f5f38e175c5e739e"}, "name": "Cindy", "age": 43}
{"_id": {"$oid": "66d7df39f5f38e175c5e739f"}, "name": "Linda", "age": 21}    
{"_id": {"$oid": "66d7df39f5f38e175c5e73a0"}, "name": "Jessca", "age": 34}
{"_id": {"$oid": "66d7de35f5f38e175c5e739d"}, "name": "Jerry", "age": 24}
显示一条
{"_id": {"$oid": "66d7de35f5f38e175c5e739c"}, "name": "Jerry", "age": 28}
{"_id": {"$oid": "66d7de35f5f38e175c5e739d"}, "name": "Jerry", "age": 24}
插入一条Jhon
{"_id": {"$oid": "66d7de35f5f38e175c5e739c"}, "name": "Jerry", "age": 28}
{"_id": {"$oid": "66d7decaf5f38e175c5e739d"}, "name": "Tom", "age": 37}
{"_id": {"$oid": "66d7df39f5f38e175c5e739e"}, "name": "Cindy", "age": 43}
{"_id": {"$oid": "66d7df39f5f38e175c5e739f"}, "name": "Linda", "age": 21}
{"_id": {"$oid": "66d7df39f5f38e175c5e73a0"}, "name": "Jessca", "age": 34}
{"_id": {"$oid": "66d7de35f5f38e175c5e739d"}, "name": "Jerry", "age": 24}    
{"_id": {"$oid": "66d9583818f1fa75230235a8"}, "name": "Jhon", "age": 40}
修改Jhon,添加年龄
{"_id": {"$oid": "66d7de35f5f38e175c5e739c"}, "name": "Jerry", "age": 28}
{"_id": {"$oid": "66d7decaf5f38e175c5e739d"}, "name": "Tom", "age": 37}
{"_id": {"$oid": "66d7df39f5f38e175c5e739e"}, "name": "Cindy", "age": 43}
{"_id": {"$oid": "66d7df39f5f38e175c5e739f"}, "name": "Linda", "age": 21}
{"_id": {"$oid": "66d7df39f5f38e175c5e73a0"}, "name": "Jessca", "age": 34}
{"_id": {"$oid": "66d7de35f5f38e175c5e739d"}, "name": "Jerry", "age": 24}
{"_id": {"$oid": "66d9583818f1fa75230235a8"}, "name": "Jhon", "age": 19}
删除一条Jhon
{"_id": {"$oid": "66d7de35f5f38e175c5e739c"}, "name": "Jerry", "age": 28}
{"_id": {"$oid": "66d7decaf5f38e175c5e739d"}, "name": "Tom", "age": 37}    
{"_id": {"$oid": "66d7df39f5f38e175c5e739e"}, "name": "Cindy", "age": 43}
{"_id": {"$oid": "66d7df39f5f38e175c5e739f"}, "name": "Linda", "age": 21}
{"_id": {"$oid": "66d7df39f5f38e175c5e73a0"}, "name": "Jessca", "age": 34}
{"_id": {"$oid": "66d7de35f5f38e175c5e739d"}, "name": "Jerry", "age": 24}

2.Python访问MongoDB

代码语言:javascript
复制
pip install pymongo

代码

代码语言:javascript
复制
from pymongo import MongoClient
 
# 连接到MongoDB实例
client = MongoClient('mongodb://192.168.31.184:27017/')
 
# 选择数据库
db = client['admin']
 
# 选择集合(类似于SQL中的表)
collection = db['person']
     
# 插入文档(类似于SQL中的记录)
#collection.insert_one({'name': 'Alice', 'age': 25})
 
# 查询文档
result = collection.find_one({'name': 'Jerry'})
print(result)    
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2024-09-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档