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

Mongoose查询指定_id价目表及嵌套数组中产品价格

解决MongoDB聚合查询返回空数组及获取指定嵌套元素的问题

问题原因

你的聚合查询返回空数组,核心原因是类型不匹配:MongoDB中存储的_id和product_id是ObjectId对象,但你传入的myPricelistVariable和myProductVariable大概率是字符串类型,导致$match阶段无法匹配到数据。

正确的聚合查询写法

先将字符串类型的ID转换为Mongoose的ObjectId类型,再执行聚合管道,就能得到你期望的格式:

const mongoose = require('mongoose');

// 转换ID类型,确保与数据库存储类型一致
const targetPricelistId = mongoose.Types.ObjectId(myPricelistVariable);
const targetProductId = mongoose.Types.ObjectId(myProductVariable);

const result = await Pricelist.aggregate([
  // 展开嵌套数组,将每个pricelist_rows元素转为独立文档
  { $unwind: '$pricelist_rows' },
  // 匹配指定价目表ID和产品ID的文档
  {
    $match: {
      _id: targetPricelistId,
      'pricelist_rows.product_id': targetProductId
    }
  },
  // 可选:指定返回字段(若Schema启用了timestamps,created_at会自动生成)
  {
    $project: {
      name: 1,
      created_at: 1,
      pricelist_rows: 1
    }
  }
]);

补充:保留原文档结构的查询方式

如果不需要将每个匹配行拆分为独立文档,而是希望返回原价目表结构、仅保留匹配的pricelist_rows元素,可以用$filter替代$unwind:

const result = await Pricelist.aggregate([
  { $match: { _id: targetPricelistId } },
  {
    $project: {
      name: 1,
      created_at: 1,
      pricelist_rows: {
        $filter: {
          input: '$pricelist_rows',
          as: 'row',
          cond: { $eq: ['$$row.product_id', targetProductId] }
        }
      }
    }
  }
]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 20:56:20