im creating a project where Im using mongoDB and I want to query some recipes.
example of recipe document in my db
I want to get recipes where "ingredients" array (sentences), have any words inside matching another array (single words).
I came up with something like this:
const recipes = await recipe
.aggregate([
// add a weight parameter based of number of ingredients matching searched ingredient
{
$project: {
name: 1,
ingredients: 1,
tags: 1,
url: 1,
weight: {
$add: [
{
$size: {
$setIntersection: ["$ingredients", ingrArr],
},
},
],
},
},
},
{ $sort: { weight: -1 } },
])
It shows recipes where there are exact strings like "flour" and I added "weight" to sort them based on number of matching words, however it would not show something like: "cup of flour".
I tried $unwind, but i couldn’t make it work.
could anybody help me?
2
Answers
I had to add regular expression array and include it in query. This happens to work like I wanted. thanks
document
query
the result added a field weight with number of matched element
or easier way to use
$text
and$search
by create text index at ingredients field and querythe result added a filed score of search