GO——mongo实现模糊查询

导入需要的包

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

构造结构体

type User struct {
	Name string
	Age  int
	City string
}
type Users struct {
	Collection *mongo.Collection
	UserInfo   map[string](*User)
}

初始化变量

var database = "mongocrud"
var table = "cruds"
var user = initMongo()

初始化mongo

func initMongo() *Users {
	users := &Users{}
	
	// Set client options
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
	
	// Connect to MongoDB
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}

	// Check the connection
	err = client.Ping(context.TODO(), nil)

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

	fmt.Println("Connected to MongoDB!")

	//获得在数据库里面User集合的handle
	collection := client.Database(database).Collection(table)
	users.Collection = collection
	users.UserInfo = map[string](*User){}

	//关闭数据库连接
	//defer client.Disconnect(context.TODO())
	//fmt.Println("Connection to MongoDB closed.")
	return users
}

实现模糊查询

func selectInfo(name string, age int, city string) []User{
	// Pass these options to the Find method
	findOptions := options.Find()

	filter := bson.D{}
	filter = append(filter, bson.E{Key: "name", Value: name})

	filter = append(filter, bson.E{
		Key: "city",
		//i 表示不区分大小写
		Value: bson.M{"$regex": primitive.Regex{Pattern: ".*"+city+".*", Options: "i"}},
	})

	filter = append(filter, bson.E{Key: "age", Value: bson.M{"$gte": age}})

	fmt.Println("filter:", filter)

	results := make([]User,0)

	cur, err := user.Collection.Find(context.TODO(), filter, findOptions)
	if err = cur.Err(); err != nil {
		fmt.Println(err)
	}

	for cur.Next(context.TODO()) {
		// create a value into which the single document can be decoded
		var elem User
		err := cur.Decode(&elem)
		if err != nil {
			fmt.Println("err decode")
			log.Fatal(err)
		}

		results = append(results, elem)
	}

	fmt.Println("results: ", results)
	return results
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

九思梦鹿

喜欢,请记得点赞或赞赏哟

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值