玩转MongoDB—使用Go和Java客户端

本文涉及的产品
云数据库 MongoDB,通用型 2核4GB
简介: 话说上一节我们说到MongoDB的基本使用,当命令行的操作我们熟悉了以后,就可以使用相关的Driver,也就是驱动程序进行相关编程语言的使用操作,因为在实际的开发过程中总归是要用编程语言来控制的,因此这篇文章我们介绍两个最常用的编程语言—Go&Java,来使用各自的驱动链接并操作MongoDB,Start!

1 都有哪些语言有MongoDB的Driver

诺,如图:
在这里插入图片描述
你以为只有这些吗?

太小看我们的工程师群体了,我们还有研究并开源的社区版本的Drivers,如Dart、Erlang、Kotlin等等

附上链接:https://www.mongodb.com/docs/drivers/community-supported-drivers/

2 Go连接MongoDB

Doc.: https://www.mongodb.com/docs/drivers/go/current/

2.1 添加依赖

go get go.mongodb.org/mongo-driver/mongo

2.2 代码

main函数

package main

import (
   "context"
   "go.mongodb.org/mongo-driver/mongo"
   "go.mongodb.org/mongo-driver/mongo/options"
)

var Coll *mongo.Collection

func main() {
   //URL规则:
   //mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
   client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://127.0.0.1:27017"))
   if err != nil {
      panic(err)
   }
   defer func() {
      if err := client.Disconnect(context.TODO()); err != nil {
         panic(err)
      }
   }()
   Coll = client.Database("test").Collection("books")
   //InsertOne()
   //InsertMany()
   //FindOne()
   //FindAny()
   //UpdateOne()
   //UpdateAny()
   DeleteOne()
}

具体代码:

package main

import (
   "context"
   "encoding/json"
   "fmt"
   "go.mongodb.org/mongo-driver/bson"
   "go.mongodb.org/mongo-driver/mongo/options"
)

//InsertOne 添加一个
func InsertOne() {
   result, err := Coll.InsertOne(
      context.TODO(),
      bson.D{
         {"type", "计算机"},
         {"name", "《MongoDB教程》"},
         {"price", 9.9},
         {"vendor", bson.A{"JD", "TB"}},
      },
   )
   if err != nil {
      panic(err)
   }
   fmt.Println(result)
}

//InsertMany 添加一批
func InsertMany() {
   docs := []interface{}{
      bson.D{{"type", "计算机"},
         {"name", "《Go教程》"},
         {"price", 19.9},
         {"vendor", bson.A{"JD", "TB"}}},
      bson.D{{"type", "人文"},
         {"name", "《人间词话》"},
         {"price", 9.9},
         {"vendor", bson.A{"PDD", "TB"}}},
      bson.D{{"type", "计算机"},
         {"name", "《Java教程》"},
         {"price", 29.9},
         {"vendor", bson.A{"JD", "TB", "PDD"}}},
      bson.D{{"type", "计算机"},
         {"name", "《Redis教程》"},
         {"price", 19.9},
         {"vendor", bson.A{"JD", "TB"}}},
   }
   result, err := Coll.InsertMany(context.TODO(), docs)
   if err != nil {
      panic(err)
   }
   fmt.Println(result)
}

//FindOne 查找一个,多个符合条件的也返回一个
func FindOne() {
   var result bson.M
   err := Coll.FindOne(context.TODO(), bson.D{{"type", "计算机"}}).Decode(&result)
   if err != nil {
      panic(err)
   }
   jsonData, err := json.MarshalIndent(result, "", "")
   if err != nil {
      panic(err)
   }
   fmt.Printf("%s\n", jsonData)
}

//FindAny 查看多个
func FindAny() {
   var result bson.M
   //取前两条
   cursor, err := Coll.Find(context.TODO(), bson.D{}, options.Find().SetLimit(2))
   if err != nil {
      panic(err)
   }
   for cursor.Next(context.TODO()) {
      cursor.Decode(&result)
      jsonData, err := json.MarshalIndent(result, "", "")
      if err != nil {
         panic(err)
      }
      fmt.Printf("%s\n", jsonData)
   }
}

//UpdateOne 修改一个
func UpdateOne() {
   result, err := Coll.UpdateOne(
      context.TODO(),
      //修改条件
      bson.D{{"price", 9.9}},
      //修改结果
      bson.D{{"$set", bson.D{{"price", 39.9}}}},
   )
   if err != nil {
      panic(err)
   }
   //修改文档的数量
   fmt.Println(result.ModifiedCount)
}

//UpdateAny 修改符合条件的多个
func UpdateAny() {
   result, err := Coll.UpdateMany(
      context.TODO(),
      //修改条件
      bson.D{{"price", 39.9}},
      //修改结果
      bson.D{{"$set", bson.D{{"price", 9.99}}}},
   )
   if err != nil {
      panic(err)
   }
   //修改文档的数量
   fmt.Println(result.ModifiedCount)
}

//DeleteOne 删除一个
func DeleteOne() {
   result, err := Coll.DeleteOne(
      context.TODO(),
      bson.D{{"name", "《Redis教程》"}},
   )
   if err != nil {
      panic(err)
   }
   //删除文档的数量
   fmt.Println(result.DeletedCount)
}

3 Java连接MongoDB

Doc.: https://www.mongodb.com/docs/drivers/java-drivers/

3.1 依赖

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-sync</artifactId>
    <version>4.6.1</version>
    <exclusions>
        <exclusion>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver-core</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.mongodb</groupId>
            <artifactId>bson</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-core</artifactId>
    <version>4.6.1</version>
    <exclusions>
        <exclusion>
            <groupId>org.mongodb</groupId>
            <artifactId>bson</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>bson</artifactId>
    <version>4.6.1</version>
</dependency>

3.2 代码

package org.ymx.sb_mongodb.cache;

import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.InsertManyResult;
import com.mongodb.client.result.InsertOneResult;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.bson.conversions.Bson;
import java.util.ArrayList;
import java.util.Arrays;
import static com.mongodb.client.model.Filters.eq;

public class MongoDBUtil {

    private String url = "mongodb://localhost:27017";

    private MongoClient client;

    private MongoCollection<Document> collection;

    public void init() {
        // 注意,这里我们配置mongos服务信息即可
        client = MongoClients.create(url);
        //获取数据库
        MongoDatabase database = client.getDatabase("test");
        // 获取集合
        collection = database.getCollection("books");
    }

    public void insertOne() {
        Document doc = new Document("type", "计算机")
                .append("name", "《JavaScript教程》")
                .append("price", 59.9)
                .append("vendor", Arrays.asList("JD", "TB"));
        InsertOneResult result = collection.insertOne(doc);
        System.out.println(result.getInsertedId());
    }

    public void findOne() {
        Bson eq = eq("type", "计算机");
        FindIterable<Document> find = collection.find(eq);
        Document first = find.first();
        System.out.println(first);
    }

    public void insertMany() {
        ArrayList<Document> documents = new ArrayList<>();
        Document doc1 = new Document("type", "历史")
                .append("name", "《人类简史》")
                .append("price", 69.9)
                .append("vendor", Arrays.asList("JD", "TB"));
        Document doc2 = new Document("type", "历史")
                .append("name", "《近代史》")
                .append("price", 29.9)
                .append("vendor", Arrays.asList("JD", "TB"));
        Document doc3 = new Document("type", "计算机")
                .append("name", "《Python教程》")
                .append("price", 59.9)
                .append("vendor", Arrays.asList("JD", "TB"));
        documents.add(doc1);
        documents.add(doc2);
        documents.add(doc3);
        InsertManyResult result = collection.insertMany(documents);
        System.out.println(result.getInsertedIds());
    }

    public void updateOne() {
        Bson bson = Filters.eq("type", "计算机");
        Bson bson1 = Updates.set("type", "科学");
        UpdateResult result = collection.updateOne(bson, bson1);
        System.out.println(result.getModifiedCount());
    }

    public void findMany() {
        FindIterable<Document> documents = collection.find();
        documents.forEach(document -> {
            System.out.println(document);
        });
    }

    public void deleteOne() {
        DeleteResult result = collection.deleteOne(eq("name", "《MongoDB教程》"));
        System.out.println(result.getDeletedCount());
    }


    public static void main(String[] args) {
        MongoDBUtil util = new MongoDBUtil();
        util.init();
        //util.insertOne();
        //util.findOne();
        //util.insertMany();
        //util.updateOne();
        //util.findMany();
        //util.deleteOne();
    }
}

4 总结

本篇文章仅展示了不同的编程语言连接MongoDB中最常用的操作,当然MongoDB的可用操作不止这些,大家还可以利用官方文档进行深入的研究。

参考:

https://www.zhangbj.com/p/670.html

相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
相关文章
|
17天前
|
JSON NoSQL Java
Redis入门到通关之Java客户端SpringDataRedis(RedisTemplate)
Redis入门到通关之Java客户端SpringDataRedis(RedisTemplate)
33 0
|
15天前
|
算法 Java Go
Go vs Java:内存管理与垃圾回收机制对比
对比了Go和Java的内存管理与垃圾回收机制。Java依赖JVM自动管理内存,使用堆栈内存并采用多种垃圾回收算法,如标记-清除和分代收集。Go则提供更多的手动控制,内存分配与释放由分配器和垃圾回收器协同完成,使用三色标记算法并发回收。示例展示了Java中对象自动创建和销毁,而Go中开发者需注意内存泄漏。选择语言应根据项目需求和技术栈来决定。
|
3天前
|
网络协议 Dubbo Java
【网络编程】理解客户端和服务器并使用Java提供的api实现回显服务器
【网络编程】理解客户端和服务器并使用Java提供的api实现回显服务器
9 0
|
13天前
|
Java
JavaFX库用于在Java中绘制K线图,适合构建富客户端应用。
JavaFX库用于在Java中绘制K线图,适合构建富客户端应用。以下是一个简单的K线图绘制示例:创建OHLCChart,设置标题和坐标轴,创建数据集并添加数据点,最后显示在Scene中。要定制图表外观,可利用JavaFX的丰富参数和方法。查阅JavaFX文档以获取更多细节。
24 3
|
13天前
|
NoSQL Java 关系型数据库
Java基础教程(21)-Java连接MongoDB
【4月更文挑战第21天】MongoDB是开源的NoSQL数据库,强调高性能和灵活性。Java应用通过MongoDB Java驱动与之交互,涉及MongoClient、MongoDatabase、MongoCollection和Document等组件。连接MongoDB的步骤包括:配置连接字符串、创建MongoClient、选择数据库和集合。伪代码示例展示了如何建立连接、插入和查询数据。
|
13天前
|
编解码 JavaScript 前端开发
【专栏】介绍了字符串Base64编解码的基本原理和在Java、Python、C++、JavaScript及Go等编程语言中的实现示例
【4月更文挑战第29天】本文介绍了字符串Base64编解码的基本原理和在Java、Python、C++、JavaScript及Go等编程语言中的实现示例。Base64编码将24位二进制数据转换为32位可打印字符,用“=”作填充。文中展示了各语言的编码解码代码,帮助开发者理解并应用于实际项目。
|
14天前
|
运维 NoSQL Java
Serverless 应用引擎产品使用之在函数计算上部署Java服务并访问阿里云MongoDB如何解决
阿里云Serverless 应用引擎(SAE)提供了完整的微服务应用生命周期管理能力,包括应用部署、服务治理、开发运维、资源管理等功能,并通过扩展功能支持多环境管理、API Gateway、事件驱动等高级应用场景,帮助企业快速构建、部署、运维和扩展微服务架构,实现Serverless化的应用部署与运维模式。以下是对SAE产品使用合集的概述,包括应用管理、服务治理、开发运维、资源管理等方面。
15 0
|
15天前
|
Java 大数据 Go
Go vs Java:在大数据处理领域的性能对比
Go与Java在大数据处理中各有特点。Go启动快,内存占用少,静态类型及并发模型(goroutine和channel)使其在并发性能上有优势。Java虽然启动慢,JVM内存占用高,但拥有丰富的生态系统和并发工具。代码示例展示了Go的goroutine和Java的线程池处理大数据的场景。在性能上,Go可能更优,但Java的跨平台性和生态广度使其仍被广泛应用。
|
15天前
|
网络协议 物联网 Java
Go与Java:在物联网领域的适用性分析
本文对比分析了Go和Java在物联网领域的适用性。Go语言因其轻量级、高效和并发特性,适合资源受限的物联网设备,特别是处理并发连接和数据流。Java则凭借跨平台性、丰富的生态系统和企业级应用能力,适用于大型物联网系统和复杂业务场景。两者在物联网领域各有优势,开发者可根据项目需求选择合适的语言。
|
NoSQL Go MongoDB
go mongodb 忽略字段,go bson 忽略字段
go mongodb 忽略字段,go bson 忽略字段
1036 0