nexequ
nexequ

Reputation: 371

How to perform $regex on "_id" in official mongodb golang package?

I'm trying to perform regex query on ObjectId() in golang "go.mongodb.org/mongo-driver/" package.

I tried so far:

query := bson.M{}
query["_id"] = primitive.Regex{
    Pattern: mySearchID,
    Options: "i",
}
opts := options.Find()
collection.Find(context.TODO(), query, opts)

It doesn't work at all.

I tried also:

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)

It also doesn't work.

How can I find documents with just part of the id?

Upvotes: 0

Views: 585

Answers (1)

D. SM
D. SM

Reputation: 14480

$regex most likely only works on strings. If you look at https://docs.mongodb.com/manual/reference/operator/query/regex/ the word "string" is italicized:

Provides regular expression capabilities for pattern matching strings in queries.

So:

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

You can use https://docs.mongodb.com/manual/reference/operator/aggregation/convert/ (and an aggregation pipeline) to convert the values to the string type:

irb(main):037:0> a['foo'].aggregate([{'$set'=>{_id:{'$convert'=>{input:'$_id',to:'string'}}}},{'$match':{_id:/606/}}
]).to_a
=> [{"_id"=>"6068e59d4896683bab61ddbe", "test"=>1}]

Note that this type converts the _id to a string, if you need it in its original ObjectId type you'll need to $convert back.

Upvotes: 1

Related Questions