Is it possible to do a query like:
db.artigo.find( { _id : ObjectId('520a504a3004bc615fcfcf16') } )
but using a regex on ObjectId?
For example, do get _ids that contains "004" on that position above.
PS. The reason is to implement a shorty service based on some fields, namely the _id. I'm trying to create an implicit "shorty" service instead of an explicit one (with a field generated for the purpose).
MongoDB uses Perl compatible regular expressions(PCRE) version 8.42 along with UTF-8 support. In MongoDB, we can do pattern matching in two different ways: With $regex Operator. Without $regex Operator.
An ObjectID is a 12-byte Field Of BSON type. The first 4 bytes representing the Unix Timestamp of the document. The next 3 bytes are the machine Id on which the MongoDB server is running. The next 2 bytes are of process id. The last Field is 3 bytes used for increment the objectid.
Use the $text query operator to perform text searches on a collection with a text index. $text will tokenize the search string using whitespace and most punctuation as delimiters, and perform a logical OR of all such tokens in the search string.
ObjectId is not a string but a special type in MongoDB. You can not query with a regex expression operator against a field that contains ObjectId's.
_id doesn't have to be an ObjectId, so what I would suggest is providing your own unique string as _id then you can use a regex the expression for querying.
Example:
let userId = 'bf44fa';
const result = await Users.aggregate([
{
$addFields: {
tempUserId: { $toString: '$_id' },
}
},
{
$match: {
tempUserId: { $regex: userId, $options: "i" }
}
}
]).exec();
Now we can find by _id with the last 6 digits or start 6 digits by using aggregation as your wish.
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