导入需要的包
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{}
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
collection := client.Database(database).Collection(table)
users.Collection = collection
users.UserInfo = map[string](*User){}
return users
}
实现模糊查询
func selectInfo(name string, age int, city string) []User{
findOptions := options.Find()
filter := bson.D{}
filter = append(filter, bson.E{Key: "name", Value: name})
filter = append(filter, bson.E{
Key: "city",
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()) {
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
}