gpt4 book ai didi

regex - 如何使用 bson 在 GoLang 中为正则表达式编写 mongodb 查询?

转载 作者:数据小太阳 更新时间:2023-10-29 03:19:50 24 4
gpt4 key购买 nike

我想使用 go mongodb 驱动程序在 mongodb 中使用名字的记录中进行通配符搜索。

我正在使用下面的查询来实现它。

filter := bson.D{{Key: "tenantId", Value: cmd.TenantID}}
if cmd.FirstNameSearch != "" {
filter = append(filter, bson.E{Key: "firstName",
Value: bson.M{"$regex": primitive.Regex{Pattern: "^" + cmd.FirstNameSearch + "$", Options: "i"}}})
}

这对我不起作用。如果我做错了什么,你能纠正我吗?

连in和不in也不行。

if len(cmd.StatusIn) > 0 {
filter = append(filter, bson.E{Key: "status", Value: bson.E{Key: "$in", Value: cmd.StatusIn}})
}
if len(cmd.StatusNotIn) > 0 {
filter = append(filter, bson.E{Key: "status", Value: bson.E{Key: "$nin", Value: cmd.StatusNotIn}})
}

cmd.StatusIn 是字符串的 slice ([]string)

最佳答案

下面是一个关于如何使用 mongo-driver 进行正则表达式查询的示例v1.0:

filter := bson.D{{Key:"foo", Value:99}}
filter = append(filter, bson.E{Key:"bar", Value: bson.D{
{"$regex", primitive.Regex{Pattern:"^ThisValue.*", Options:"i"}},
}},
)
cursor, err := collection.Find(context.Background(), filter )

上面的例子还附加了一个BSON element bson.E对于 BSON Document bson.D筛选。类似于你的例子。

我建议检查您正在解码查询结果的结构,和/或集合中是否有匹配的文档。

关于regex - 如何使用 bson 在 GoLang 中为正则表达式编写 mongodb 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55740288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com