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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Golang 编译成DLL文件的操作

    Golang 编译成DLL文件的操作

    这篇文章主要介绍了Golang 编译成DLL文件的操作方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-05-05
  • GO项目配置与使用的方法步骤

    GO项目配置与使用的方法步骤

    本文主要介绍了GO项目配置与使用的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧<BR>
    2022-06-06
  • 部署Go语言项目的 N 种方法(小结)

    部署Go语言项目的 N 种方法(小结)

    这篇文章主要介绍了部署Go语言项目的 N 种方法(小结),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-11-11
  • Golang接口型函数使用小结

    Golang接口型函数使用小结

    接口函数指的是用函数实现接口,这样在调用的时候就会非常简便,这种方式适用于只有一个函数的接口,这里以迭代一个map为例,演示这一实现的技巧,对Golang接口型函数使用知识感兴趣的朋友一起看看吧
    2022-06-06
  • Go使用select切换协程入门详解

    Go使用select切换协程入门详解

    这篇文章主要为大家介绍了Go使用select切换协程入门详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-08-08
  • golang如何实现三元运算符功能

    golang如何实现三元运算符功能

    这篇文章主要介绍了在其他一些编程语言中,如 C 语言,三元运算符是一种可以用一行代码实现条件选择的简便方法,那么在Go语言中如何实现类似功能呢,下面就跟随小编一起学习一下吧
    2024-02-02
  • Go语言单控制器和多控制器使用详解

    Go语言单控制器和多控制器使用详解

    这篇文章主要为大家详细介绍了Go语言单控制器和多控制器的使用方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-07-07
  • Go语言中使用gorm小结

    Go语言中使用gorm小结

    这篇文章主要给大家介绍了Go语言中如何使用gorm,文中介绍的很详细,有需要的朋友们可以参考借鉴,下面来一起看看吧。
    2016-12-12
  • golang atomic原子操作示例详解

    golang atomic原子操作示例详解

    这篇文章主要为大家介绍了golang atomic原子操作示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-09-09
  • golang实战之truncate日志文件详解

    golang实战之truncate日志文件详解

    这篇文章主要给大家介绍了关于golang实战之truncate日志文件的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-07-07

最新评论