I have several documents in a collection in MongoDB as shown in this snapshot . I'm creating a web app for which this is the back-end data.
Every document has an attribute name
. The user has an option to search for the name
in the front-end. Now, suppose the user searches for "Sam", then I'm returning the documents where name
is either exactly "Sam" or starts with "Sam". I have implemented this using the following code:
let name = "^"+req.body.name;
const name_regex = new RegExp(name, 'gi');
try {
let members = await Member.find({ name: req.body.name=="" ? /^$|/ : name_regex});
res.send(members);
}
ie, if the user dosen't provide a name, return all documents, else return documents matching the regex.
So , if the user searches for "Sam", the output is all 3 documents since all of them have name
starting with "Sam", but if the user searches for "Samm", then only one document is returned where the name
is "Sammy".
Now, I want to implement the same logic on age
attribute, ie, if the user searches for age: 2, then I want to return all documents where age is either exactly 2 or starts with the digit 2. But I'm unable to use the above method sine it only works with strings.
Note: I'm using mongoose package and Express framework.
You can do this:
// regular expression matching anything that starts with two
const age_regex = /^2/;
Member.find({
$expr: {
$regexMatch: {
input: {
$toString: "$age" // Casting the age value to a string
},
regex: age_regex
}
}
})
Some usefule explanatory links: $expr , $regexMatch , $toString
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.