簡體   English   中英

MongoDB - 根據其屬性查找最匹配的文檔

[英]MongoDB - finding most matching document based on its properties

我正在嘗試根據多個字段查找具有最相似文檔的文檔。

例子:

帶文檔的集合:

{ _id: 1, dept: "tech", description: "lime green computer",contact:"John",no:"2763926932" }
{ _id: 2, dept: "tech", description: "wireless red mouse",contact:"Adam",no:"2434358465" }
{ _id: 3, dept: "kitchen", description: "green placemat",contact:"Bruce",no:"2763934932" }
{ _id: 4, dept: "kitchen", description: "red peeler",contact:"Tom",no:"27639343932" }
{ _id: 5, dept: "food", description: "green apple",contact:"Clark",no:"2763934532" }
{ _id: 6, dept: "food", description: "red potato",contact:"Tony",no:"2963926932" }

這里每個字段都有一個加權:

部門:10 描述:7 聯系人:4

因此,如果我使用 dept = tech、description = lime green computer 和 contact= Tony 搜索文檔

它應該返回 _id =1 的文檔,即

{ _id: 1, dept: "tech", description: "lime green computer",contact:"John",no:"2763926932" }

它嘗試創建索引並將權重添加到此處指定的每個字段。

db.blog.createIndex(
   {
     dept: "text",
     description: "text",
     contact: "text",
     no:"text"
   },
   {
     weights: {
       dept: 10,
       description: 7,
         contact:4
     },
     name: "TextIndex"
   }
 )

但是當我嘗試查詢數據庫時,它無法匹配任何文檔。

能否請您提供解決此問題的方法。

使用$text運算符對使用文本索引編制索引的字段的內容執行文本搜索。

db.blog.find({$text:{$search:"tech lime green computer Jhon"}}, { score: { $meta: "textScore" } });

{  "_id" : 2,  "dept" : "tech",  "description" : "wireless red mouse",  "contact" :     "Adam",  "no" : "2434358465",  "score" : 11 }
{  "_id" : 1,  "dept" : "tech",  "description" : "lime green computer",  "contact" : "John",  "no" : "2763926932",  "score" : 25 }
{  "_id" : 3,  "dept" : "kitchen",  "description" : "green placemat",  "contact" : "Bruce",  "no" : "2763934932",  "score" : 5.25 }
{  "_id" : 5,  "dept" : "food",  "description" : "green apple",  "contact" : "Clark",  "no" : "2763934532",  "score" : 5.25 }

MongoDB 返回所有搜索詞匹配的所有文檔。 { score: { $meta: "textScore" } }表達式提供有關$text操作處理的信息。

要僅搜索特定文檔,您可以將field:value添加到您的查詢中。

db.blog.find(
    { dept: "tech", $text:{$search:"tech lime green computer Jhon" } }, 
    { score: { $meta: "textScore" } })
.sort( { score: { $meta: "textScore" } } )

{  "_id" : 1,  "dept" : "tech",  "description" : "lime green computer",  "contact" : "John",  "no" : "2763926932",  "score" : 25 }
{  "_id" : 2,  "dept" : "tech",  "description" : "wireless red mouse",  "contact" : "Adam",  "no" : "2434358465",  "score" : 11 }

https://docs.mongodb.com/manual/reference/operator/query/text/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM