Java Python访问MongoDB

2024-09-10 16:21:01 浏览数 (1)

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)    

0 人点赞