How to get all the values that contains part of a string using mongoose find?
Solution 1:
You almost answered this yourself in your tags. MongoDB has a $regex
operator which allows a regular expression to be submitted as a query. So you query for strings containing "Alex" you do this:
Books.find(
{ "authors": { "$regex": "Alex", "$options": "i" } },
function(err,docs) {
}
);
You can also do this:
Books.find(
{ "authors": /Alex/i },
function(err,docs) {
}
);
Both are valid and different to how you tried in the correct supported syntax as shown in the documentation.
But of course if you are actually asking "how to get the 'array' results only for those that match 'Alex' somewhere in the string?" then this is a bit different.
Complex matching for more than one array element is the domain of the aggregation framework ( or possibly mapReduce, but that is much slower ), where you need to "filter" the array content.
You start of much the same. The key here is to $unwind
to "de-normalize" the array content in order to be alble to "filter" properly as individual documents. Then re-construct the array with the "matching" documents.
Books.aggregate(
[
// Match first to reduce documents to those where the array contains the match
{ "$match": {
"authors": { "$regex": "Alex", "$options": i }
}},
// Unwind to "de-normalize" the document per array element
{ "$unwind": "$authors" },
// Now filter those document for the elements that match
{ "$match": {
"authors": { "$regex": "Alex", "$options": i }
}},
// Group back as an array with only the matching elements
{ "$group": {
"_id": "$_id",
"title": { "$first": "$title" },
"authors": { "$push": "$authors" },
"subjects": { "$first": "$subjects" }
}}
],
function(err,results) {
}
)
Solution 2:
Find the posts with title containing : cool
, and case insensitive
match: (Very Cool
have cool
also)
const s = 'cool'
const regex = new RegExp(s, 'i') // i for case insensitive
Posts.find({title: {$regex: regex}})
Solution 3:
Live search using mongoose and $regex
Below is the query to get the books starts with the search text.
var result = await Books.find({ 'authors': { $regex: '^' + search_text, $options: 'i' } }).exec();