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.industryCategoriesin the$map, we wrap it with a$filteroperator. - The
$filterchecks each element ($$cat) in theindustryCategoriesarray and only keeps those whereisDefaultequalstrue.
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
相关产品推荐
相关产品推荐

