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

MongoDB聚合脚本中如何在$map内过滤isDefault:false数据

Solution to Filter isDefault: false Entries in MongoDB Aggregation

Got it, let's tweak your aggregation pipeline to only keep the industryCategories entries where isDefault is true. The key change is adding a $filter stage inside your $map to sift out the unwanted entries.

Here's the updated code:

db.brand.aggregate([
  {
    $lookup: {
      from: "industryCategoryMapping",
      as: 'Category',
      let: { entityId: { $toString : '$_id' }},
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                { $eq: ['$type', 'BRAND'] },
                { $eq: ['$$entityId', '$entityId'] },
              ]
            }
          }
        }
      ]
    }
  },
  {
    $project: {
      name: 1,
      industryCategoryMapping: {
        $map: {
          input: "$Category",
          as: "each",
          in: {
            $filter: {
              input: "$$each.industryCategories",
              as: "cat",
              cond: { $eq: ["$$cat.isDefault", true] }
            }
          }
        }
      }
    }
  },
])

What changed?

  • Instead of directly returning $$each.industryCategories in the $map, we wrap it with a $filter operator.
  • The $filter checks each element ($$cat) in the industryCategories array and only keeps those where isDefault equals true.

Expected Result

Your output will now look like this, with only the isDefault: true entry retained:

{
  "_id" : ObjectId("5dfb18a6dfb32f87deeffa13"),
  "name" : "Gatorade",
  "industryCategoryMapping" : [
    [
      {
        "_id" : ObjectId("5dd26e6e34d10718f843caa9"),
        "isDefault" : true,
        "industryCategory" : {
          "_id" : ObjectId("5def644605ea8b5a7c97b48c"),
          "industryCategory" : { "_id" : ObjectId("5def644605ea8b5a7c97b48f") }
        }
      }
    ]
  ]
}

Optional tweak: If you want to flatten the nested array (since the current result is an array of arrays), you could add an extra stage like this after the $project:

{
  $addFields: {
    industryCategoryMapping: { $concatArrays: "$industryCategoryMapping" }
  }
}

This would turn [[...]] into [...] for cleaner output.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:14:20