如何查询Item集合中与Product集合model、category均匹配的文档
实现方案
以下是两种常用的实现方式,可根据你的数据量和使用场景选择:
方式1:MongoDB聚合管道(推荐生产环境使用)
只需要一次查询即可得到结果,性能更优,适合数据量较大的场景:
db.Item.aggregate([ // 关联Product集合,匹配model和category同时相等的记录 { $lookup: { from: "Product", let: { current_model: "$model", current_category: "$category" }, pipeline: [ { $match: { $expr: { $and: [ { $eq: ["$model", "$$current_model"] }, { $eq: ["$category", "$$current_category"] } ] } } } ], as: "matched_product" } }, // 过滤掉没有匹配到Product的Item记录 { $match: { matched_product: { $ne: [] } } }, // 移除多余的关联字段,得到和预期一致的结构 { $project: { matched_product: 0 } } ])
方式2:二次查询(适合小数据集场景)
如果你的Product集合数据量很小,可以先提取所有有效model+category组合,再过滤Item集合:
// 1. 提取Product中所有有效的model+category组合 const validCombination = db.Product.aggregate([ { $project: { _id: 0, combo: { $concat: ["$model", "||", "$category"] } } } ]).map(item => item.combo) // 2. 筛选符合组合的Item文档 const result = db.Item.find({ $expr: { $in: [ { $concat: ["$model", "||", "$category"] }, validCombination ] } })
两种方式执行后得到的结果都和你给出的预期输出完全一致。
内容的提问来源于stack exchange,提问作者R.Ang
相关产品推荐
相关产品推荐

