如何通过MongoDB获取过滤后产品及价格范围并按创建时间排序
仅用MongoDB实现过滤文档并返回价格统计结果
当然可以仅通过MongoDB的聚合框架实现这个需求,不需要额外代码处理。下面是针对你的需求编写的聚合查询,同时满足按createdAt从新到旧排序的要求:
聚合查询代码
db.products.aggregate([ // 筛选目标类别文档 { $match: { category: { $in: ['mug', 'glass'] } } }, // 按createdAt降序排序(最新文档在前) { $sort: { createdAt: -1 } }, // 分面处理:同时保留文档列表和计算价格统计 { $facet: { filteredDocs: [{}], // 承接排序后的所有文档 priceStats: [ { $group: { _id: null, minPrice: { $min: '$price' }, maxPrice: { $max: '$price' } } } ] } }, // 展开文档列表,将每个文档转为单独记录 { $unwind: '$filteredDocs' }, // 合并文档列表与统计结果到统一结构 { $group: { _id: null, docList: { $push: '$filteredDocs' }, stats: { $first: '$priceStats' } } }, // 展开统计结果数组 { $unwind: '$stats' }, // 将统计对象追加到文档列表末尾 { $project: { _id: 0, finalResult: { $concatArrays: ['$docList', ['$stats']] } } }, // 展开最终结果数组 { $unwind: '$finalResult' }, // 将数组元素转为根文档输出 { $replaceRoot: { newRoot: '$finalResult' } } ])
代码逻辑说明
$match:用$in匹配多个目标类别,完成基础过滤。$sort:基于createdAt字段降序排列,确保最新文档优先展示。$facet:核心分流步骤,分别处理文档留存和价格统计两个分支。- 后续的
$unwind、$group、$concatArrays等操作,是为了把统计结果对象追加到过滤后的文档列表末尾,最终输出你需要的格式。
预期执行结果
(假设createdAt字段符合排序逻辑)
[ { name: 'blue mug', category: 'mug', price: 150, createdAt: ISODate("2024-05-20T10:00:00Z") }, { name: 'red mug', category: 'mug', price: 100, createdAt: ISODate("2024-05-19T10:00:00Z") }, { name: 'large glass', category: 'glass', price: 200, createdAt: ISODate("2024-05-18T10:00:00Z") }, { name: 'small glass', category: 'glass', price: 75, createdAt: ISODate("2024-05-17T10:00:00Z") }, { minPrice: 75, maxPrice: 200 } ]
内容的提问来源于stack exchange,提问作者Petar
相关产品推荐
相关产品推荐

