gpt4 book ai didi

mongodb - 获取 MongoDB 聚合框架中数组交集的大小

转载 作者:行者123 更新时间:2023-12-03 09:27:09 25 4
gpt4 key购买 nike

我目前正在 Java Web 应用程序中使用 MongoDB 的聚合框架,根据其他用户的偏好为用户生成推荐。

我使用的主要方法之一是查看数组交集。

现在,如果两个用户具有非零数组交集,我的算法就会简单地认为两个用户“相似”。

为了构建更准确的算法,我想权衡聚合管道中集合交集的大小。

有办法做到这一点吗?

最佳答案

如果我理解您的问题,您将获得如下数据:

db.users.insert({_id: 100, likes: [
'pina coladas',
'long walks on the beach',
'getting caught in the rain'
]})
db.users.insert({_id: 101, likes: [
'cheese',
'bowling',
'pina coladas'
]})
db.users.insert({_id: 102, likes: [
'pina coladas',
'long walks on the beach'
]})
db.users.insert({_id: 103, likes: [
'getting caught in the rain',
'bowling'
]})
db.users.insert({_id: 104, likes: [
'pina coladas',
'long walks on the beach',
'getting caught in the rain'
]})

并且您希望计算给定用户与其他用户有多少匹配特征(本例中为“喜欢”)?以下聚合管道将完成此任务:

user = 100
user_likes = db.users.findOne({_id: user}).likes
return_only = 2 // number of matches to return

db.users.aggregate([
{$unwind: '$likes'},
{$match: {
$and: [
{_id: {$ne: user}},
{likes: {$in: user_likes}}
]
}},
{$group: {_id: '$_id', common: {$sum: 1}}},
{$sort: {common: -1}},
{$limit: return_only}
])

鉴于上面的示例输入数据,这将输出以下结果,显示前 2 个匹配项:

{
"result" : [
{
"_id" : 104,
"common" : 3
},
{
"_id" : 102,
"common" : 2
}
],
"ok" : 1
}

请注意,我假设您只需要顶部的这么多匹配项,因为可能有大量用户。 $sort 步骤后跟 $limit 步骤将完成此操作。如果情况并非如此,那么您可以省略管道中的最后两个步骤。

我希望这有帮助!如果您还有其他问题,请告诉我。

布鲁斯

关于mongodb - 获取 MongoDB 聚合框架中数组交集的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18070241/

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