演示结构体
type Score struct {
Subject string `bson:"subject" json:"subject"`
Score int `bson:"score" json:"score"`
Level int `bson:"level" json:"level"`
}
type Test struct {
Id string `bson:"_id" json:"id"`
Name string `bson:"name" json:"name"`
Scores []Score `bson:"scores" json:"scores"`
}
建立连接
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
fmt.Println(err)
}
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
fmt.Println(err)
}
fmt.Println("Connected to MongoDB!")
collection := client.Database("test").Collection("chun_test")
and查询
查询id=1 and name=“test”
var condition bson.A
condition = append(condition, bson.E{Key: "_id",Value:1})
condition = append(condition, bson.E{Key: "name",Value:"test"})
cursor, err = collection.Find(ctx, condition, opts)
if err == mongo.ErrNoDocuments {
return nil
}
if err != nil {
return err
}
var tests []*Test
if err := cursor.All(ctx, &tests); err != nil {
return err
}
或查询
查询 name=“test” 或者 “test2”
condition := bson.A{}
condition = append(condition, bson.E{Key: "name",Value:"test"})
condition = append(condition, bson.E{Key: "name",Value:"test2"})
filter := bson.D{{"$or", condition,},}
cursor, err = collection.Find(ctx, filter, opts)
if err == mongo.ErrNoDocuments {
return nil
}
if err != nil {
return err
}
var tests []*Test
if err := cursor.All(ctx, &tests); err != nil {
return err
}
in查询
查询 name in(“test1”,“test2”,“test3”)
names := []string{"test1","test2","test3"}
filter := bson.A{}
filter = append(filter, bson.E{Key: "name", Value: bson.D{{"$in", names}}})
cursor, err = collection.Find(ctx, filter, opts)
if err == mongo.ErrNoDocuments {
return nil
}
if err != nil {
return err
}
var tests []*Test
if err := cursor.All(ctx, &tests); err != nil {
return err
}
模糊查询
查询name中包含 test字符串的数据
name := "test"
filter := bson.M{"name": bson.M{"$regex":primitive.Regex{Pattern:".*"+name+".*", Options: "i"}}}
cursor, err = collection.Find(ctx, filter, opts)
if err == mongo.ErrNoDocuments {
return nil
}
if err != nil {
return err
}
var tests []*Test
if err := cursor.All(ctx, &tests); err != nil {
return err
}