如何在 MongoDB 中找到类似的文档?

How can I find similar documents in MongoDB?

我的食物数据库列表类似于:

 {
   Name: "burger",
   ingredients: [
     {Item:"bread"},
     {Item:"cheese"},
     {Item:"tomato"}
   ]
 }

如何找到 ingredients 中项目最相似的文档?

最好的机会是将成分存储在文本字段中,即: {ingredients : "bread cheese tomato"} 然后你必须使用 text index and query for similarity db.your_collection.find({$text: {$search: {"tomato" }}, {score: { $meta: "textScore" }}).sort({score : {$meta: "textScore" } } ) 并获取最相关的文档

首先,您的数据应该按如下方式重构:

{
  name: "Burger",
  ingredients: [
    "bread",
    "cheese",
    "tomato",
    "beef"
  ]
}

额外的 "Item" 不会添加任何附加信息,也不会以任何方式帮助访问数据。

接下来,您需要创建一个text index。文档指出

text indexes can include any field whose value is a string or an array of string elements.

所以我们只需做一个

db.collection.ensureIndex({"ingredients":"text"})

现在我们可以做一个 $text search:

db.collection.find(
  { $text: { $search: "bread beef" } },
  { score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } )

哪个应该给你最相关的文件。

但是,您还可以对直接匹配项进行非文本搜索:

db.collection.find({ingredients:"beef"})

或多种成分

db.collections.find({ ingredients: { $all: ["beef","bread"] } })

因此,对于用户输入的搜索,您可以使用文本搜索,对于所选成分的搜索,您可以使用非文本搜索。