返回数组比较的比例
问题描述:
我有一个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%
}
]
答
简而言之,你想要$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 ] } ]
}
}
}
}}
])
总体保持不变的原则,虽然。
“由阵列的总长度除以比赛的数量等于匹配百分比”
有东西,你相信没有解决您的问题提供答案吗?如果是这样,请评论答案以澄清究竟需要解决的问题。如果它确实回答了你问的问题,那么请注意[接受你的答案](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)给你的问题问 –