猿问

如何在官方mongodb golang包中的“_id”上执行$regex?

我正在尝试在golang“go.mongodb.org/mongo-driver/”包中的ObjectId()上执行正则表达式查询。


到目前为止,我尝试了:


query := bson.M{}

query["_id"] = primitive.Regex{

    Pattern: mySearchID,

    Options: "i",

}

opts := options.Find()

collection.Find(context.TODO(), query, opts)

它根本不起作用。


我也试过了:


query := bson.M{}

query["_id"] = bson.D{

    {

        Key:   "$regex",

        Value: mySearchID,

    },

    {

        // i is for case insensitive

        Key:   "$options",

        Value: "i",

    },

}

opts := options.Find()

collection.Find(context.TODO(), query, opts)

它也不起作用。


如何仅包含部分 ID 的文档?


临摹微笑
浏览 127回答 1
1回答

慕桂英546537

$regex很可能只适用于字符串。如果你看一下 https://docs.mongodb.com/manual/reference/operator/query/regex/ 单词“字符串”是斜体的:为查询中的模式匹配字符串提供正则表达式功能。所以:irb(main):034:0> a['foo'].find.first=> {"_id"=>BSON::ObjectId('6068e59d4896683bab61ddbe'), "test"=>1}irb(main):035:0> a['foo'].find(_id: /606/).first=> nil可以使用 https://docs.mongodb.com/manual/reference/operator/aggregation/convert/(和聚合管道)将值转换为字符串类型:irb(main):037:0> a['foo'].aggregate([{'$set'=>{_id:{'$convert'=>{input:'$_id',to:'string'}}}},{'$match':{_id:/606/}}]).to_a=> [{"_id"=>"6068e59d4896683bab61ddbe", "test"=>1}]请注意,此类型将_id转换为字符串,如果在其原始 ObjectId 类型中需要它,则需要将其$convert。
随时随地看视频慕课网APP

相关分类

Go
我要回答