How can I find similar documents in MongoDB?

可紊 提交于 2021-02-19 06:19:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!