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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With