go mongo常见几种查询

演示结构体

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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值