基于MongoDB实现菜谱网站的相似菜谱推荐功能
菜谱推荐功能实现方案(MongoDB + Node.js)
MongoDB 聚合查询语句
要实现基于关键词匹配度的菜谱推荐,我们可以使用 MongoDB 的聚合管道计算每个菜谱与目标菜谱的关键词匹配数量,并按匹配度排序。假设当前菜谱的 _id 为 currentRecipeId,关键词数组为 ["Dessert","Snacks","Oven","Easy"],查询语句如下:
db.Recipe.aggregate([ // 排除当前打开的菜谱 { $match: { _id: { $ne: ObjectId("currentRecipeId") } } }, // 计算与目标关键词的匹配数量 { $addFields: { matchCount: { $size: { $setIntersection: ["$Keywords", ["Dessert","Snacks","Oven","Easy"]] } } } }, // 过滤掉完全不匹配的菜谱(可选,提升查询效率) { $match: { matchCount: { $gt: 0 } } }, // 按匹配数量降序排序(匹配度高的在前) { $sort: { matchCount: -1 } }, // 限制返回推荐结果数量(比如取前10个) { $limit: 10 }, // 选择需要返回的字段(可选) { $project: { name: 1, timeToCook: 1, proteinsContent: 1, Keywords: 1, matchCount: 1, _id: 1 } } ])
Node.js 后端实现
使用 MongoDB 官方驱动编写推荐功能的异步函数,接收当前菜谱的 _id 和关键词数组作为参数:
const { MongoClient, ObjectId } = require('mongodb'); // 假设已建立数据库连接,client 为全局连接实例 async function getRecommendedRecipes(currentRecipeId, targetKeywords) { const db = client.db('你的数据库名称'); const recipeCollection = db.collection('Recipe'); const aggregationPipeline = [ { $match: { _id: { $ne: new ObjectId(currentRecipeId) } } }, { $addFields: { matchCount: { $size: { $setIntersection: ["$Keywords", targetKeywords] } } } }, { $match: { matchCount: { $gt: 0 } } }, { $sort: { matchCount: -1 } }, { $limit: 10 }, { $project: { name: 1, timeToCook: 1, proteinsContent: 1, Keywords: 1, matchCount: 1 } } ]; return await recipeCollection.aggregate(aggregationPipeline).toArray(); }
关键细节说明
- 匹配数量计算:使用
$setIntersection取两个关键词数组的交集,再用$size获取交集长度,即为匹配关键词的数量。 - 排除当前菜谱:通过
$match过滤掉_id与当前菜谱相同的文档,避免推荐自身。 - 性能优化:为
Keywords字段创建多键索引,可以大幅提升关键词匹配的查询效率:db.Recipe.createIndex({ Keywords: 1 }) - 灵活调整:可根据需求修改
$limit的值控制推荐数量,或调整$project字段决定返回的菜谱信息。
内容的提问来源于stack exchange,提问作者user20305852
相关产品推荐
相关产品推荐

