我无法让官方 go mongo 驱动程序成功返回通过正则表达式查询查询的对象。
我已经知道如何通过 mongo shell 进行操作并获得预期的结果。在这个例子中,我得到了所有在“文本”字段中包含“他”的条目:
db.getCollection('test').find({"text": /he/})
Run Code Online (Sandbox Code Playgroud)
与此相同:
db.getCollection('test').find({"text": {$regex: /he/, $options: ''}})
Run Code Online (Sandbox Code Playgroud)
这是我当前不起作用的代码:
package main
import (
"context"
"fmt"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(5*time.Second))
defer cancel()
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
fmt.Println(err)
return
}
err = client.Connect(ctx)
if err != nil {
fmt.Println(err)
return
}
db := client.Database("test")
coll := db.Collection("test")
filter := bson.D{{"text", primitive.Regex{Pattern: "/he/", Options: ""}}}
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second) …
Run Code Online (Sandbox Code Playgroud)