Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find/Count documents by partial _id value in MongoDB

I want to find documents in my collections via partial _id values that I enter in a GUI application.
After some searching I found out that I could at least find documents by it's partial id using the following filter:

{ $where: "this._id.str.match(/5a.*/)" }

(where 5a is the partial id value the user entered)

My server application that handles these searches also supports pagination so I always query the database to count/estimate the number of matching documents.
If I however put this $where expression into my FilterDefinition that I pass to CountDocumentsAsync() of my collection, I just get an exception:

MongoDB.Driver.MongoCommandException: Command aggregate failed: $where is not allowed in this context

I then looked up the countDocuments method of MongoDB and found out that the $where operator is not allowed in countDocuments() and one should use $expr instead.

Unfortunately I couldn't get anything working with $expr as I couldn't find any useful examples that would help me with my specific requirements.
I just tried to wrap the $where expression in an $expr expression but that doesn't seem to work (Command aggregate failed: Unrecognized expression '$where')

Can anyone help me out on this?

like image 387
TorbenJ Avatar asked Jul 11 '26 18:07

TorbenJ


1 Answers

Assuming your _id is of ObjectId type, you can convert it to string (available from v4.0) then regex it without using expensive javascript evaluation:

db.collection.aggregate([
    { $addFields: { 
        _idString: { $toString: "$_id" } 
    } },
    { $match: { _idString: /5a.*/ } }
] )

As a side note, the regexp /5a.*/ matches exactly same strings as /5a/ does.

like image 138
Alex Blex Avatar answered Jul 13 '26 11:07

Alex Blex