首页 > 其他分享 >【go】【mongo】

【go】【mongo】

时间:2024-05-06 17:36:23浏览次数:16  
标签:mongo err cursor context go bson

@

目录


写在前面

  • 相关博文
  • 个人博客首页
  • 免责声明:仅供学习交流使用!开源框架可能存在的风险和相关后果将完全由用户自行承担,本人不承担任何法律责任。

[install]

https://www.mongodb.com/zh-cn/docs/drivers/go/current/quick-reference/

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

[connection]

https://www.mongodb.com/zh-cn/docs/drivers/go/current/fundamentals/connections/connection-guide/

	// To configure auth via a URI instead of a Credential, use
	// "mongodb://ldap-user:ldap-pwd@localhost:27017/?authMechanism=PLAIN".
	credential := options.Credential{
		//AuthMechanism: "PLAIN",
		Username: username,
		Password: password,
	}

	clientOpts := options.Client().ApplyURI(fmt.Sprintf("mongodb://%s:%d", host, port)).SetAuth(credential)
``
## document
### create one 
```go
		user := bson.M{"name": "user1", "age": 18, "six": true, "info": "info 1 any to be command"}
		result, err := c.InsertOne(context.TODO(), user)

create many

		users := []any{
			bson.M{"name": "user2", "age": 18, "six": true, "info": "info 2 any to be command"},
			bson.M{"name": "user3", "age": 18, "six": true, "info": "info 3 any to be command"},
			bson.M{"name": "user4", "age": 18, "six": true, "info": "info 4 any to be command"},
			bson.M{"name": "user5", "age": 18, "six": true, "info": "info 5 any to be command"},
		}
		result, err := c.InsertMany(context.TODO(), users)

create delete one

		filter := bson.M{"age": bson.M{"$gt": 18}}
		result, err := c.DeleteOne(context.TODO(), filter)

delete many

		filter := bson.M{}
		result, err := c.DeleteMany(context.TODO(), filter)

update one

		filter := bson.M{"name": "user1"}
		update := bson.M{"$inc": bson.M{"age": 1}}
		result, err := c.UpdateOne(context.TODO(), filter, update)
	

update many

		filter := bson.M{"age": bson.M{"$gte": 25}}
		update := bson.M{"$inc": bson.M{"age": -10}}
		result, err := c.UpdateMany(context.TODO(), filter, update)

find one

		var result Users
		filter := bson.M{"age": bson.M{"$lt": 19}}
		err := c.FindOne(context.TODO(), filter).Decode(&result)

find many Next

		var results []Users
		course, err := c.Find(context.TODO(), bson.M{})
		
		defer course.Close(context.TODO())
		for course.Next(context.TODO()) {
			var result Users
			err := course.Decode(&result)
			results = append(results, result)
		}
	})

find many All

		filter := bson.M{"$and": []bson.M{
			{"age": bson.M{"$gte": 18}},
			//{"name": "2"},
		}}
		course, err := c.Find(context.TODO(), filter)
		var results []Users
		err = course.All(context.TODO(), &results)

find many filter

		filter := bson.M{"$text": bson.M{"$search": "info"}}
		cursor, err := c.Find(context.TODO(), filter)
		defer cursor.Close(context.TODO())
			var result []Users
			errs := cursor.All(context.TODO(), &result)

建立索引

coll := client.Database("sample_mflix").Collection("movies")
indexModel := mongo.IndexModel{
    Keys: bson.D{{"title", 1}},
}
name, err := coll.Indexes().CreateOne(context.TODO(), indexModel)
if err != nil {
    panic(err)
}
fmt.Println("Name of Index Created: " + name)

查询单条索引

package main

import (
	"context"
	"fmt"
	"log"
	"regexp"

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

func main() {
	// MongoDB服务连接配置
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

	// 连接到MongoDB
	client, err := mongo.Connect(context.Background(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Disconnect(context.Background())

	// 指定数据库和集合
	collection := client.Database("yourDatabase").Collection("yourCollection")

	// 构建查询条件,使用正则表达式检索特定字符
	// 下面的例子是查找fieldname字段中包含"specificString"字符的文档
	regex := bson.M{"$regex": regexp.QuoteMeta("specificString")}
	filter := bson.M{"fieldname": regex}

	// 执行查询
	cursor, err := collection.Find(context.Background(), filter)
	if err != nil {
		log.Fatal(err)
	}
	defer cursor.Close(context.Background())

	// 遍历查询结果
	var results []YourStructType
	if err = cursor.All(context.Background(), &results); err != nil {
		log.Fatal(err)
	}

	// 打印查询结果
	for _, result := range results {
		fmt.Printf("Found document: %+v\n", result)
	}
}

// YourStructType 应该是匹配你MongoDB集合中文档结构的Go struct
type YourStructType struct {
	Fieldname string `bson:"fieldname"`
	// 添加更多字段...
}

查询全部索引

创建索引

index := mongo.IndexModel{
    Keys: bson.M{"$**": "text"}, // 这个索引将覆盖所有字段
}
collection := client.Database("yourDatabase").Collection("yourCollection")
indexName, err := collection.Indexes().CreateOne(context.Background(), index)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Created index named: %s\n", indexName)

查询全部索引

collection := client.Database("yourDatabase").Collection("yourCollection")

// 构建查询条件
query := bson.M{"$text": bson.M{"$search": "specificString"}}

// 执行查询,这将在所有字段上应用文本搜索
cursor, err := collection.Find(context.Background(), query)
if err != nil {
    log.Fatal(err)
}
defer cursor.Close(context.Background())

// 遍历结果
for cursor.Next(context.Background()) {
	var result bson.M // 或者你自己的结构体类型
	if err := cursor.Decode(&result); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Found document: %+v\n", result)
}

// 检查遍历过后是否有错误发生
if err := cursor.Err(); err != nil {
	log.Fatal(err)
}

分页索引

package main

import (
	"context"
	"fmt"
	"log"

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

func main() {
	// MongoDB服务连接配置
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
	client, err := mongo.Connect(context.Background(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Disconnect(context.Background())

	// 指定数据库和集合
	collection := client.Database("yourDatabase").Collection("yourCollection")

	// 设置分页参数
	pageSize := 10 // 每页文档数量
	pageNumber := 1 // 获取第几页,这里为例子只获取第一页

	// 创建分页查询的options
	findOptions := options.Find().
		SetSkip(int64((pageNumber - 1) * pageSize)).
		SetLimit(int64(pageSize))

	// 进行分页查询
	cursor, err := collection.Find(context.Background(), bson.D{{}}, findOptions)
	if err != nil {
		log.Fatal(err)
	}
	defer cursor.Close(context.Background())

	// 遍历查询结果
	for cursor.Next(context.Background()) {
		// 在这里定义你的结构体以匹配集合格式
		var document bson.M // 也可以换成YourStructType
		if err := cursor.Decode(&document); err != nil {
			log.Fatal(err)
		}
		fmt.Println(document) // 打印文档
	}

	// 检查遍历过后是否有错误发生
	if err := cursor.Err(); err != nil {
		log.Fatal(err)
	}
}

正则表达

package main

import (
	"context"
	"fmt"
	"log"
	"regexp"

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

func main() {
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
	client, err := mongo.Connect(context.Background(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Disconnect(context.Background())

	collection := client.Database("yourDatabase").Collection("yourCollection")

	// 使用正则表达式构建查询条件
	specificString := "searchString"
	filter := bson.M{
		"$or": []bson.M{
			{"field1": bson.M{"$regex": regexp.QuoteMeta(specificString), "$options": "i"}},
			{"field2": bson.M{"$regex": regexp.QuoteMeta(specificString), "$options": "i"}},
			// 为更多字段添加相同结构的正则表达式条件
		},
	}

	cursor, err := collection.Find(context.Background(), filter)
	if err != nil {
		log.Fatal(err)
	}
	defer cursor.Close(context.Background())

	for cursor.Next(context.Background()) {
		var result bson.M // 或者你的自定义结构体类型
		if err := cursor.Decode(&result); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("Found document: %+v\n", result)
	}

	if err := cursor.Err(); err != nil {
		log.Fatal(err)
	}
}

// 定义一个与你的文档结构相匹配的Go struct类型
type YourDocumentType struct {
	Field1 string `bson:"field1"`
	Field2 string `bson:"field2"`
	// 其他字段
}

索引检索

index := mongo.IndexModel{
    Keys: bson.M{
        "field1": "text",
        "field2": "text",
        // 为更多字段添加"text"索引
    },
}
_, err := collection.Indexes().CreateOne(context.Background(), index)
if err != nil {
    // 处理错误
}
filter := bson.M{"$text": bson.M{"$search": "searchString"}}
cursor, err := collection.Find(context.Background(), filter)
// 处理错误和遍历结果 cursor 的代码与之前相同
// 文本索引有一些限制,比如不能在文本索引字段中使用通配符"$**"创建索引。
// 因此,如果你需要对所有字段进行文本搜索,可能需要一个更复杂的解决方案,或者使用正则表达式的方法。再次强调,正则表达式方法通常不如文本索引效率高,特别是在缺少索引的大型数据库中,所以在使用前请评估性能方面的需求和成本。


mongo bson 动态数据 难度

  • bson.M是一个map,你可以像在Go中修改任何其他map一样来修改它。
    示例:添加、更新、删除字段
// 创建一个bson.M对象
doc := bson.M{"name": "John", "age": 30, "city": "New York"}

// 更新字段
doc["age"] = 31

// 添加新字段
doc["gender"] = "male"

// 删除字段
delete(doc, "city")

fmt.Println(doc)
  • bson.D是一个有序的元素列表,每一个元素都是bson.E或bson.Element类型,包含键和值。修改bson.D通常需要遍历元素列表。

示例:更新bson.D中的字段
// 创建一个bson.D对象
doc := bson.D{{"name", "John"}, {"age", 30}, {"city", "New York"}}

// 更新age字段
for i, elem := range doc {
    if elem.Key == "age" {
        doc[i] = bson.E{Key: "age", Value: 31}
    }
}

fmt.Println(doc)

// 假设根据某些业务逻辑,我们需要动态地添加字段到文档中
fieldsToAdd := map[string]interface{}{
	"name":      "Dynamic John",
	"timestamp": time.Now().Unix(),
	"tags":      []string{"dynamic", "data", "go"},
}

// 将map中的字段添加到bson.D类型的文档中
for key, value := range fieldsToAdd {
	dynamicDoc = append(dynamicDoc, bson.E{Key: key, Value: value})
}

参考资料

基础/标准库/第三方库


golang 导航


编程规范


算法|面试


项目


标签:mongo,err,cursor,context,go,bson
From: https://www.cnblogs.com/nones/p/18153204

相关文章

  • 跨域请求解决办法(Django)
    跨域请求解决办法(Django)1.安装第三方扩展:pipinstalldjango-cors-headerssettings.py里面操作2.添加应用:INSTALLED_APPS=(...'corsheaders',...)3.第三步,添加中间件,注意放在第一条,第一时间进行处理:MIDDLEWARE=['corsheaders.middleware.......
  • 【go】【Elasticsearch】
    @目录写在前面[install][connection][low-level]index[createindex][updateindex][indexingdocuments][deleteindex]document[insertdocuments][searchdocuments][updatedocument][deletedocument][full-type][connection][common]index[createindex][deleteindex][upda......
  • django 表单
    实现方式一:将具体的search操作放到views首先,在app下面新建一个forms.py文件,用于定义表单。创建了一个名为"SearchCaseForm"的表单,并定义了一个名为“case_name”的CharFieldfromdjangoimportformsclassSearchCaseForm(forms.Form): case_name=forms.CharField()创建......
  • golang 获得一个结构体的字节大小
    golang的内存占用是如何构成的呢?unsafe.SizeOf()转载:如何在Go中获取变量的内存大小?--CSDN问答如果传递一个未初始化的变量,unsafe.Sizeof()与reflect.Type.Size()将只返回传递的变量的类型的大小,并不递归地遍历数据结构并增加所指向变量的大小。切片是一个相对简单的结构体st......
  • 我用 GitHub 9.8k 的 Go 语言 2D 游戏引擎写了个游戏
    前言hi,大家好,这里是白泽。今天给大家分享一个GitHub......
  • [992] Remove holes within polygons in a shapefile
    Toremoveholeswithinpolygonsinashapefile,youcanusethegeopandaslibraryinPython.Here'showyoucandoit:importgeopandasasgpd#Readtheshapefilegdf=gpd.read_file('path_to_shapefile.shp')#Removeholeswithinpolygon......
  • uwsgi+nginx启动Django静态文件设置
    总体思路:设置好STATIC_ROOT后使用pythonmanager.pycollectstatic命令将django下所有的静态文件搜集到STATIC_ROOT下,然后让nginx的static路由指向这个目录1.Django的settings.py文件中设置如下STATIC_URL='/static/'STATIC_ROOT=os.path.join(BASE_DIR,'staticfiles'......
  • 用Golang做一个永久阻塞,有哪些小技巧 ?
    用Golang做一个永久阻塞,有哪些小技巧?磊丰 Go语言圈 2024-05-0608:30 广东 听全文Go语言圈Go语言开发者的学习好助手,分享Go语言知识,技术技巧,学习与交流Go语言开发经验,互动才有助于技术的提升,每天5分钟,助你GO语言技术快乐成长159篇原创内容公众号......
  • [ARC159F] Good Division
    题意给定一个长度为\(2\timesn\)的数列\(S\)。称一个数列是好的,当且仅当数列中的数可以由每次删除相邻两个不同的数的操作删空。求划分该数列为若干好的字串的方案数。Sol集中注意力。首先显然长度为奇数的序列是没法做的。若序列存在绝对众数,则该序列一定无法删除......
  • 深入学习和理解Django模板层:构建动态页面
    title:深入学习和理解Django模板层:构建动态页面date:2024/5/520:53:51updated:2024/5/520:53:51categories:后端开发tags:Django模板表单处理静态文件国际化性能优化安全防护部署实践第一章:模板语法基础Django模板语法介绍Django模板语法是一种简洁而......