如何调整MongoDB查询,提取inventory集合内嵌的入库数据?
解决方案
方案一:将Ingreso类型的entries展开为顶层文档数组
使用MongoDB聚合管道可直接实现该需求,核心步骤如下:
$match:先过滤掉已删除的文档$unwind:将每个文档内的movements.entries数组拆分为单个独立文档$match:筛选出type为Ingreso的条目$replaceRoot:把筛选后的条目内容直接提升为顶层文档$sort:按需求排序(可调整字段)
对应代码:
return this.connect().then((db) => { return db .collection(collection) .aggregate([ { $match: { is_deleted: false } }, { $unwind: "$movements.entries" }, { $match: { "movements.entries.type": "Ingreso" } }, { $replaceRoot: { newRoot: "$movements.entries" } }, { $sort: { created_at: -1 } } ]) .toArray(); });
方案二:将entries数组提升至文档顶层
若无需展开单个条目,仅需把entries从movements层级提到顶层,可通过投影操作直接映射字段:
对应代码:
return this.connect().then((db) => { return db .collection(collection) .find({ is_deleted: false }) .project({ _id: 1, entries: "$movements.entries" }) .sort({ _id: -1 }) .toArray(); });
补充说明
- 方案一通过拆分+替换根文档,完全匹配你想要的「单个条目作为顶层文档数组」格式
- 方案二仅调整字段层级,保留原文档的
_id和entries数组结构,满足次优需求
内容的提问来源于stack exchange,提问作者jecorrales
相关产品推荐
相关产品推荐

