You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于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();
}

关键细节说明

  1. 匹配数量计算:使用 $setIntersection 取两个关键词数组的交集,再用 $size 获取交集长度,即为匹配关键词的数量。
  2. 排除当前菜谱:通过 $match 过滤掉 _id 与当前菜谱相同的文档,避免推荐自身。
  3. 性能优化:为 Keywords 字段创建多键索引,可以大幅提升关键词匹配的查询效率:
    db.Recipe.createIndex({ Keywords: 1 })
    
  4. 灵活调整:可根据需求修改 $limit 的值控制推荐数量,或调整 $project 字段决定返回的菜谱信息。

内容的提问来源于stack exchange,提问作者user20305852

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 14:01:02