gpt4 book ai didi

java - 查询 MongoDB 数组并使用最匹配的元素进行排序

转载 作者:行者123 更新时间:2023-12-01 17:29:18 25 4
gpt4 key购买 nike

我需要您就以下情况提供专业知识。

我有一个这样的集合:

"array" : {
"item" : 1,
"1" : [100, 130, 255],
}

"array" : {
"item" : 2,
"1" " [0, 70, 120],
}

"array" : {
"item" : 3,
"1" : [100, 90, 140],

}

我正在查询这个集合:

 db.test.find(array.1 : {$in : [100, 80, 140]});

这会返回项目编号 1 和 3,因为它将提供的数组中的任何值与集合中的值相匹配。不过,我想对这个数组进行排序,以给出具有更多相似数字的结果。结果应分别为第 3 项和第 1 项。

但是,我可以获取结果并使用 k 最近邻算法对数组进行排序。然而,处理巨大的数据集使得这种情况非常不可取(或者是吗?)MongoDB 中是否有任何函数可以提供此功能?我正在使用Java,有什么算法可以足够快地实现这一点吗?如有任何帮助,我们将不胜感激。

谢谢。

最佳答案

您可以使用聚合框架来做到这一点,尽管这并不容易。问题在于聚合框架中没有 $in 运算符。因此,您必须以编程方式匹配数组中的每个项目,这会变得非常困惑。 编辑:重新排序,使匹配项排在第一位,以防 $in 帮助您过滤掉大部分内容。

db.test.aggregate(
{$match:{"array.1":{$in:[100, 140,80]}}}, // filter to the ones that match
{$unwind:"$array.1"}, // unwinds the array so we can match the items individually
{$group: { // groups the array back, but adds a count for the number of matches
_id:"$_id",
matches:{
$sum:{
$cond:[
{$eq:["$array.1", 100]},
1,
{$cond:[
{$eq:["$array.1", 140]},
1,
{$cond:[
{$eq:["$array.1", 80]},
1,
0
]
}
]
}
]
}
},
item:{$first:"$array.item"},
"1":{$push:"$array.1"}
}
},
{$sort:{matches:-1}}, // sorts by the number of matches descending
{$project:{matches:1, array:{item:"$item", 1:"$1"}}} // rebuilds the original structure
);

输出:

{
"result" : [
{
"_id" : ObjectId("50614c02162d92b4fbfa4448"),
"matches" : 2,
"array" : {
"item" : 3,
"1" : [
100,
90,
140
]
}
},
{
"_id" : ObjectId("50614bb2162d92b4fbfa4446"),
"matches" : 1,
"array" : {
"item" : 1,
"1" : [
100,
130,
255
]
}
}
],
"ok" : 1
}

如果您将 matches 字段保留在最后的 $project 之外,则可以将其保留在结果之外。

关于java - 查询 MongoDB 数组并使用最匹配的元素进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12576948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com