2017-08-01 108 views
1

我有一個mongodb存儲庫,有很多數據,我需要搜索和分類給定的數據。返回數組比較的比例

我打算讓服務器工作來處理請求並給出響應,但我不知道使用哪種算法,bigdata工具甚至mongodb命令。

這是我需要做的一個例子。

我有這個數據庫:

[ 
    { 
     id: 1, 
     Colors: ["Green","Red","Blue","Yellow"] 
    }, 
    { 
     id: 2, 
     Colors: ["Green","Red","Blue"] 
    }, 
    { 
     id: 3, 
     Colors: ["Green","Red"] 
    }, 
    { 
     id: 4, 
     Colors: ["Green"] 
    } 
] 

然後,我有這個輸入

String x = "Green Red" 

或類似

{ Colors: ["Green","Red"]} 

一個JSON然後它會返回匹配該數據輸入:

[ 
    { 
     id: 4, 
     Colors: ["Green"], 
     Matches: 100% 
    } 
    { 
     id: 3, 
     Colors: ["Green","Red"], 
     Matches: 100% 
    }, 
    { 
     id: 2, 
     Colors: ["Green","Red","Blue"], 
     Matches: 66% 
    }, 
    { 
     id: 1 
     Colors: ["Green","Red","Blue","Yellow"], 
     Matches: 50% 
    } 
] 
+0

有東西,你相信沒有解決您的問題提供答案嗎?如果是這樣,請評論答案以澄清究竟需要解決的問題。如果它確實回答了你問的問題,那麼請注意[接受你的答案](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)給你的問題問 –

回答

0

簡而言之,你想要$filter這個數組來自源輸入的正匹配,然後將得到的$size與原來的比較。技術版本之間略有不同,但基本上是:

db.getCollection('junk').aggregate([ 
    { "$addFields": { 
    "Matches": { 
     "$trunc": { 
     "$multiply": [ 
      { "$divide": [ 
      { "$size": { 
       "$filter": { 
       "input": "$Colors", 
       "as": "c", 
       "cond": { "$in": [ "$$c", ["Green","Red"] ] } 
       } 
      }}, 
      { "$size": "$Colors" } 
      ]}, 
      100 
     ] 
     } 
    } 
    }} 
]) 

你也許可以,只要有$setIntersection脫身,而不是使用$filter作爲比較值和陣列都包含「獨一無二」的元素。

db.getCollection('junk').aggregate([ 
    { "$addFields": { 
    "Matches": { 
     "$trunc": { 
     "$multiply": [ 
      { "$divide": [ 
      { "$size": { 
       "$setIntersection": [ "$Colors", ["Green", "Red"] ] 
      }}, 
      { "$size": "$Colors" } 
      ]}, 
      100 
     ] 
     } 
    } 
    }} 
]) 

如果你沒有$trunc$floor你可以做使用$mod$subtract丟棄剩餘數學:

db.getCollection('junk').aggregate([ 
    { "$project": { 
    "id": 1, 
    "Colors": 1, 
    "Matches": { 
     "$let": { 
     "vars": { 
      "perc": { 
      "$multiply": [ 
       { "$divide": [ 
       { "$size": { 
        "$setIntersection": [ "$Colors", ["Green", "Red"] ] 
       }}, 
       { "$size": "$Colors" } 
       ]}, 
       100 
      ] 
      } 
     }, 
     "in": { 
      "$subtract": [ "$$perc", { "$mod": [ "$$perc", 1 ] } ]  
     } 
     } 
    } 
    }} 
]) 

總體保持不變的原則,雖然。

「由陣列的總長度除以比賽的數量等於匹配百分比」