Golang查询MongoDB的实现步骤

 更新时间:2025年12月15日 10:44:48   作者:喵了几个咪  
本文介绍了如何使用Golang操作MongoDB数据库,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

连接 MongoDB 非常简单,只需连接 MongoDB 生成的 uri。

然后我们可以使用 client.Database() 函数来确保我们连接到正确的数据库。

package main

import (
	"context"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		log.Fatal(err)
	}

	db := client.Database("testdb")

	// disconnect the mongo client when main is completed
	defer func() {
		if err = client.Disconnect(ctx); err != nil {
			panic(err)
		}
	}()
}

我们可以使用Ping方法来真正确保我们连接到正确的数据库。

ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

err = client.Ping(ctx, readpref.Primary())

使用 Golang 向 MongoDB 插入文档

要将文档插入 MongoDB,我们可以使用MongoDB 提供的 bson.D。但为了使操作更简单、更贴近实际应用,我们将使用bson注解标注struct

我们使用的模型是:

type Car struct {
	Id    primitive.ObjectID `bson:"_id"`
	Brand string             `bson:"brand"`
	Model string             `bson:"model"`
	Year  int                `bson:"year"`
}

然后我们可以简单地使用 InsertOne()方法 将文档插入 MongoDB。

package main

import (
	"context"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type Car struct {
	Id        primitive.ObjectID `bson:"_id"`
    CreatedAt time.Time          `bson:"createdAt"`
	Brand     string             `bson:"brand"`
	Model     string             `bson:"model"`
	Year      int                `bson:"year"`
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		log.Fatal(err)
	}

	db := client.Database("testdb")

	exampleData := Car{
		Id:    primitive.NewObjectID(),
        CreatedAt: time.Now().UTC(),
		Brand: "Mercedes",
		Model: "G-360",
		Year:  2002,
	}

	res, err := db.Collection("cars").InsertOne(context.Background(), exampleData)
	if err != nil {
		log.Fatal(err)
	}

	// inserted id is ObjectID("639b62ae2518fbd9315e405d")
	log.Printf("inserted id is %v", res.InsertedID)
}

使用 Golang 向 MongoDB 写入多个文档

我们可以使用 Collection对象 的 InsertMany()方法。但是,InsertMany()方法需要传入[]interface{}参数。

package main

import (
	"context"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type Car struct {
	Id        primitive.ObjectID `bson:"_id"`
    CreatedAt time.Time          `bson:"createdAt"`
	Brand     string             `bson:"brand"`
	Model     string             `bson:"model"`
	Year      int                `bson:"year"`
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		log.Fatal(err)
	}

	db := client.Database("testdb")

	var data []interface{}
	data = append(data, Car{
		Id:    primitive.NewObjectID(),
        CreatedAt: time.Now().UTC(),
		Brand: "Toyota",
		Model: "Corolla",
		Year:  2008,
	})
	data = append(data, Car{
		Id:    primitive.NewObjectID(),
        CreatedAt: time.Now().UTC(),
		Brand: "Ford",
		Model: "Focus",
		Year:  2021,
	})

	res, err := db.Collection("cars").InsertMany(context.Background(), data)
	if err != nil {
		log.Fatal(err)
	}

	// 2 documents inserted
	log.Printf("%v documents inserted", len(res.InsertedIDs))
}

使用 Golang 从 MongoDB 中查找单个文档

要查找符合条件的单个文档,我们可以使用*Collection对象的 FindOne()方法。

package main

import (
	"context"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type Car struct {
	Id        primitive.ObjectID `bson:"_id"`
    CreatedAt time.Time          `bson:"createdAt"`
	Brand     string             `bson:"brand"`
	Model     string             `bson:"model"`
	Year      int                `bson:"year"`
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		log.Fatal(err)
	}

	db := client.Database("testdb")

    condition := bson.M{}
    cur, err := db.Collection("cars").FindOne(context.Background(), condition)
	if err != nil {
		log.Fatal(err)
	}

	var data []Car
	if err := cur.All(context.Background(), &data); err != nil {
		log.Fatal(err)
	}

	// now we can use the data array, which contains all of the documents
	for _, car := range data {
		log.Printf("the brand is %v\n", car.Brand)
	}
}

获取最后创建的文档

我们还可以将 mongo.Options 传递给 Find()方法。

假设我们想要获取最后插入的文档。

  • 我们需要按createdAt字段排序
  • 它应该是降序的,这就是我们将排序值设为-1的原因。

使用 Golang 从 MongoDB 中查找所有文档

要查找集合中的所有文档,我们可以使用*Collection对象的Find()方法。

在下面的示例中,我们没有指定任何条件,这意味着返回数据库中的所有文档。

package main

import (
	"context"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type Car struct {
	Id        primitive.ObjectID `bson:"_id"`
    CreatedAt time.Time          `bson:"createdAt"`
	Brand     string             `bson:"brand"`
	Model     string             `bson:"model"`
	Year      int                `bson:"year"`
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		log.Fatal(err)
	}

	db := client.Database("testdb")

    condition := bson.M{}
    cur, err := db.Collection("cars").Find(context.Background(), condition)
	if err != nil {
		log.Fatal(err)
	}

	var data []Car
	if err := cur.All(context.Background(), &data); err != nil {
		log.Fatal(err)
	}

	// now we can use the data array, which contains all of the documents
	for _, car := range data {
		log.Printf("the brand is %v\n", car.Brand)
	}
}

查找符合条件的多个文档

如果我们想返回brandToyota,那么我们可以将condition变量更改为

condition := bson.M{
    "brand": "Toyota"
}

在查找操作中使用Projection

如果要在Find()方法中使用Projection,我们可以使用mongo.Options参数。

假设我们想返回 2 个字段

  1. 返回汽车的品牌brand
  2. 返回一个布尔字段isNew来检查汽车是否是新的(1. 如果汽车的生产年份是 2022 年,那么它是新的; 2. 否则,它就旧了。)。

使用SetProjection()方法来设置Projection字段的值:

var opts = options.Find().SetProjection(
		bson.M{
			"brand": 1,
			"isNew": bson.M{
				"$cond": bson.M{
					"if": bson.M{"$gte": bson.A{"$year", 2022}}, 
					"then": true, 
					"else": false},
			},
		})
cur, err := db.Collection("cars").Find(context.Background(), bson.M{}, opts)

使用 Golang 更新 MongoDB 中的单个文档

要更新单个文档,我们应该使用FindOneAndUpdate()UpdateOne()操作。在本文中,我们将使用FindOneAndUpdate()方法来进行操作。

package main

import (
	"context"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		log.Fatal(err)
	}

	db := client.Database("testdb")

	filter := bson.M{
		"brand": "Toyota",
		"model": "Corolla",
	}

	update := bson.M{
		"year": 2022,
	}

	res := db.Collection("cars").FindOneAndUpdate(context.Background(), filter, update)

	if res.Err() != nil {
		log.Fatal(err)
	}

	// operation successful
}

如何在 MongoDB 中返回更新的文档?

我们可以使用mongo.Options包来实现这一点。我们应该将返回文档的选项SetReturnDocument设置为after

opts := options.FindOneAndUpdate().SetReturnDocument(options.After)

res := db.Collection("cars").FindOneAndUpdate(context.Background(), filter, update, opts)

// we can use the updated car document
var updatedData Car

if err := res.Decode(&updatedData); err != nil {
	log.Fatal(err)
}

使用 Golang 从 MongoDB 中删除文档

要删除文档,我们可以使用*Collection对象的DeleteOne()方法。

要删除多个文档,我们可以使用*Collection对象的DeleteMany()方法。

package main

import (
	"context"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		log.Fatal(err)
	}

	db := client.Database("testdb")

	filter := bson.M{
		"brand": "Toyota",
		"model": "Corolla",
	}

	// for single document
	res, err := db.Collection("cars").DeleteMany(context.Background(), filter)

	if err != nil {
		log.Fatal(err)
	}

	// 1 document is deleted.
	log.Printf("%v document is deleted", res.DeletedCount)
}

原文地址

MongoDB & Golang Query Examples - Cheat Sheet

到此这篇关于 Golang查询MongoDB的实现步骤的文章就介绍到这了,更多相关 Golang查询MongoDB内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Go语言中的数据格式(json、xml 、msgpack、protobuf)使用总结

    Go语言中的数据格式(json、xml 、msgpack、protobuf)使用总结

    在分布式的系统中,因为涉及到数据的传输,所以一定会进行数据的交换,此时就要定义数据交换的格式,例如二进制、Json、Xml等等。本文总结了Go语言中的数据格式,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-07-07
  • Golang中omitempty关键字的具体实现

    Golang中omitempty关键字的具体实现

    本文主要介绍了Golang中omitempty关键字的具体实现,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • Golang错误处理:异常捕捉和恢复机制

    Golang错误处理:异常捕捉和恢复机制

    Golang中,异常处理是通过 defer + panic + recover 的方式来实现的,使用 defer 可以将清理操作注册到函数执行完毕后执行,而 panic 和 recover 可以用于处理异常,通过组合使用这些功能,可以实现更加健壮的程序
    2024-01-01
  • 关于Go你不得不知道的一些实用小技巧

    关于Go你不得不知道的一些实用小技巧

    开发语言上Go成为高并发业务开发的主流语言,再加上云原生技术底座的驱动,Go语言风光无限,下面这篇文章主要给大家介绍了关于Go你不得不知道的一些实用小技巧,需要的朋友可以参考下
    2022-11-11
  • 使用go xorm来操作mysql的方法实例

    使用go xorm来操作mysql的方法实例

    今天小编就为大家分享一篇关于使用go xorm来操作mysql的方法实例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-04-04
  • Golang对sqlite3数据库进行操作实践记录

    Golang对sqlite3数据库进行操作实践记录

    sqlite是嵌入式关系型数据库引擎,官方描述为自包含的、无服务的、零配置并支持事务的关系型数据库引擎,下面这篇文章主要给大家介绍了关于Golang对sqlite3数据库进行操作的相关资料,需要的朋友可以参考下
    2024-03-03
  • golang之go.mod与go.sum作用及说明

    golang之go.mod与go.sum作用及说明

    Go模块系统通过go.mod和go.sum解决依赖管理问题,实现版本隔离、可重现构建、依赖下载优化及安全验证,提升项目协作与构建的可靠性和安全性
    2025-08-08
  • Golang使用Swagger文档教程详解

    Golang使用Swagger文档教程详解

    这篇文章主要为大家详细介绍Golang使用Swagger文档教程的相关知识,文中通过示例代码讲解详细,具有一定的借鉴价值,感兴趣的小伙伴可以学习一下
    2023-12-12
  • Go语言中的sync包同步原语最新详解

    Go语言中的sync包同步原语最新详解

    Go语言在sync包中提供了一套多才多艺的同步机制,以及用于管理对共享资源的并发访问的原子操作,了解这些工具并为您的并发需求选择合适的工具是编写高效可靠的并发Go程序的关键,这篇文章主要介绍了Go语言中的`sync`包同步原语,需要的朋友可以参考下
    2023-12-12
  • Go语言读取文本文件的三种方式总结

    Go语言读取文本文件的三种方式总结

    工作中时不时需要读取文本,文本文件是最常见的文件类型。本文将利用Go语言从逐行、逐个单词和逐个字符三个方法读取文件,感兴趣的可以了解一下
    2023-01-01

最新评论