如何在 MongoDB 中找到类似的文档? [英] How can I find similar documents in MongoDB?

查看:57
本文介绍了如何在 MongoDB 中找到类似的文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似于以下内容的食物数据库列表:

I have food db listing similar to:

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

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

How can I find documents that have the most similar items in ingredients?

推荐答案

首先,你的数据应该如下重构:

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 索引可以包含值为字符串或字符串元素数组的任何字段.

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

所以我们只做一个

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

现在我们可以进行$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"})

或多种成分

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.

这篇关于如何在 MongoDB 中找到类似的文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆