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

从MongoDB按分类关联查询并列出产品的技术需求

从MongoDB检索分类及对应产品的解决方案

需求概述

需从MongoDB中查询分类数据,并关联每个分类下的产品,最终返回包含分类名称和对应产品列表的结构化数据,格式示例如下:

[
  {
   "category_name": "分类名称",
   "products": [
      {
        "product_name": "产品名称",
        "image": ["图片路径1", "图片路径2"],
        // 按需保留其他产品字段
      },
      ...
    ]
  },
  ...
]

集合结构说明

Category集合文档结构

{
  "_id": ObjectId("62c827b5a427b63741da9175"),
  "name": {
    "en": "Home"
  }
}

Product集合文档结构

{
  "_id": ObjectId("648714ca2c67a70008c616db"),
  "categories": [ObjectId("649911fc0e298800088d0214")],
  "image": ["1000047887.png","1000047889.jpg"],
  "tag": ["[]"],
  "category": ObjectId("648702f958cc2d0008cda715"),
  "name": "Product A"
}

聚合查询语句

使用MongoDB聚合框架,通过关联操作实现分类与产品的匹配:

场景1:按产品的单个category字段关联

db.Category.aggregate([
  // 关联Product集合,匹配分类ID与产品的category字段
  {
    $lookup: {
      from: "Product",
      localField: "_id",
      foreignField: "category",
      as: "products"
    }
  },
  // 投影并格式化返回字段
  {
    $project: {
      _id: 0,
      category_name: "$name.en",
      products: {
        $map: {
          input: "$products",
          as: "product",
          in: {
            product_name: "$$product.name",
            image: "$$product.image",
            tag: "$$product.tag"
          }
        }
      }
    }
  },
  // 可选:过滤无产品的分类
  {
    $match: {
      products: { $ne: [] }
    }
  }
])

场景2:按产品的categories数组关联(产品属于多分类)

db.Category.aggregate([
  {
    $lookup: {
      from: "Product",
      let: { categoryId: "$_id" },
      pipeline: [
        {
          $match: {
            $expr: { $in: ["$$categoryId", "$categories"] }
          }
        },
        {
          $project: {
            _id: 0,
            product_name: "$name",
            image: "$image",
            tag: "$tag"
          }
        }
      ],
      as: "products"
    }
  },
  {
    $project: {
      _id: 0,
      category_name: "$name.en",
      products: 1
    }
  },
  // 可选:过滤无产品的分类
  {
    $match: {
      products: { $ne: [] }
    }
  }
])

语句说明

  1. $lookup阶段:实现Category与Product集合的关联,将匹配到的产品存入products数组。
  2. $project阶段:重命名分类名称为category_name,并筛选产品需要返回的字段。
  3. $match阶段:可选步骤,用于剔除没有关联产品的分类条目。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 19:57:39