问题
I have food db listing similar to:
{
Name: "burger",
ingredients: [
{Item:"bread"},
{Item:"cheese"},
{Item:"tomato"}
]
}
How can I find documents that have the most similar items in ingredients
?
回答1:
First of all, your data should be remodelled as below:
{
name: "Burger",
ingredients: [
"bread",
"cheese",
"tomato",
"beef"
]
}
The extra "Item" does not add any additional information nor does it help accessing the data in any way.
Next, you need to create a text index. The docs state that
text
indexes can include any field whose value is a string or an array of string elements.
So we simply do a
db.collection.ensureIndex({"ingredients":"text"})
Now we can do a $text search:
db.collection.find(
{ $text: { $search: "bread beef" } },
{ score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } )
which should give you the most relevant documents.
However, what you could also do is a non-text search for direct matches:
db.collection.find({ingredients:"beef"})
or for multiple ingredients
db.collections.find({ ingredients: { $all: ["beef","bread"] } })
So for searching by user input, you can use the text search and for search by selected ingredients, you can use the non-text search.
回答2:
your best chance is if you store ingredients in a text field i.e: {ingredients : "bread cheese tomato"} then you have to use a text index and query for similarity db.your_collection.find({$text: {$search: {"tomato" }}, {score: { $meta: "textScore" }}).sort({score: {$meta: "textScore" } } ) and get most relevant documents
来源:https://stackoverflow.com/questions/29616781/how-can-i-find-similar-documents-in-mongodb