duanhuang7591 2019-03-28 13:25
浏览 243
已采纳

在mongodb-go-driver中通过子字符串正则表达式查询查找条目

I can't get the official go mongo driver to successfully return objects that are queried via a regex query.

I already know how to do it via the mongo shell and get my expected results. With this example i get all entries that contain "he" in their 'text' field:

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

same with this one:

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

This is my current code that doesn't work:

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")
}

Per example in the official mongo-go-driver repository, this should work.

My current entries in the collection just contain 2 fields, the id field and an extra text field. I currently have 3 entries. that look like this:

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

My expected results with the code from above, should be the first 2 entries. Instead i get an empty cursor back.

Does anybode know, what i am doing wrong? Thanks for your help.

  • 写回答

1条回答 默认 最新

  • douzhi4311 2019-03-28 14:03
    关注

    primitive.Regex struct accepts Pattern value without slashes, so it must be:

    filter := bson.D{{"text", primitive.Regex{Pattern: "he", Options: ""}}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵