9

我无法让官方 go mongo 驱动程序成功返回通过正则表达式查询查询的对象。

我已经知道如何通过 mongo shell 进行操作并获得预期的结果。通过这个例子,我得到了所有在“文本”字段中包含“他”的条目:

db.getCollection('test').find({"text": /he/})

与此相同:

db.getCollection('test').find({"text": {$regex: /he/, $options: ''}})

这是我当前不起作用的代码:

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)
    defer cancel()

    cur, err := coll.Find(ctx, filter)
    if err != nil {
        fmt.Println(err)
        return
    }

    i := 0
    for cur.Next(ctx) {
        i = i + 1
    }
    fmt.Println("Found", i, "elements")
}

根据官方 mongo-go-driver 存储库中的示例,这应该可以工作。

我当前在集合中的条目只包含 2 个字段,id 字段和一个额外的文本字段。我目前有 3 个条目。看起来像这样:

{
    "_id" : ObjectId("5c9cc7e9950198ceeefecbdd"),
    "text" : "hello world"
},
{
    "_id" : ObjectId("5c9cc7f6950198ceeefecbec"),
    "text" : "hello"
},
{
    "_id" : ObjectId("5c9cc804950198ceeefecbfa"),
    "text" : "test world"
}

我对上面代码的预期结果应该是前两个条目。相反,我得到一个空光标。

有谁知道,我做错了什么?谢谢你的帮助。

4

1 回答 1

22

primitive.Regexstruct 接受Pattern不带斜线的值,因此它必须是:

filter := bson.D{{"text", primitive.Regex{Pattern: "he", Options: ""}}}
于 2019-03-28T14:03:11.233 回答