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

如何调整MongoDB查询,提取inventory集合内嵌的入库数据?

解决方案

方案一:将Ingreso类型的entries展开为顶层文档数组

使用MongoDB聚合管道可直接实现该需求,核心步骤如下:

  1. $match:先过滤掉已删除的文档
  2. $unwind:将每个文档内的movements.entries数组拆分为单个独立文档
  3. $match:筛选出type为Ingreso的条目
  4. $replaceRoot:把筛选后的条目内容直接提升为顶层文档
  5. $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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 21:50:22