I want to make a universal search where I search the db with a given text
for a particular company. I have a products collection with each document having following fields
{
_id: '',
company: 'Amazon'
category: 'Apparels',
category1: 'Boys',
tags: ['cotton', 'linen', 'handwash'], // random length array
attribute: 'Style'
}.... many more such documents
input fields:
text = 'cotton'
name ='Amazon'
I have tried the following query to search any match for the given text in category, category1, tags, attribute
Query
db.products.aggregate([
{
$match: {
"company": 'Amazon',
$or: [
{"attribute": { $regex: text, $options: "i"}},
{"category": { $regex: text, $options: "i" }},
{"category1": { $regex: text, $options: "i" }},
{"tags": { $regex: text, $options: "i" }}
]
}
}
]);
I am not sure if this works for array tags , is this the correct way to compare regex against all array items?
Note : I do not want to use find queries, pure aggregation is needed
You can use the same However, the following may give you better solution.
let text = 'Style'
let name = 'Amazon'
let regexString = "^" + text + "$";
db1.products.aggregate([
{
$match: {
"company": name,
$or: [
{ "attribute": { $regex: regexString } },
{ "category": { $regex: regexString } },
{ "category1": { $regex: regexString } },
{ "tags": { $regex: regexString } },
]
}
}
]).toArray()
.then(re => res.json({ result: re }))
.catch(err => res.json(err));
This will match exactly the same text. if you use ^
it will search for strings starting with the particular text and $
will search for strings ending with text value.
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.