A variable in regular expressions (regex) for MongoDB's aggregate function can be utilized in several ways:
Example:
const regexPattern = "foo|bar";
db.collection.aggregate([
{
$match: {
field: {
$regex: regexPattern
}
}
}
]);
Example:
const regexPattern = /foo(\d)/;
db.collection.aggregate([
{
$project: {
result: {
$regexFind: {
input: "$field",
regex: regexPattern,
options: "i"
}
}
}
}
]);
Example:
const searchKeyword = "foo";
const regexPattern = new RegExp(".*" + searchKeyword + ".*", "i");
db.collection.aggregate([
{
$match: {
field: {
$regex: regexPattern
}
}
}
]);
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-05-28 11:00:00 +0000
Seen: 15 times
Last updated: Oct 16 '22
What is the process of integrating API data into MongoDB using Spark/Python?
How can additional fields that have been transformed be queried in MongoDB?
What is the difference between indexing in Elasticsearch and MongoDB?
When data is updated in MongoDB, why does Logstash not reflect the changes?
How can the Mongo Operator be used to deploy MongoDB in EKS/EFS?
How can data be extracted from Azure DocumentDB for exporting purposes?
How can I link or integrate mongodb with Google Data Studio?