Mongodb 用于匹配集合中子文档的参考模型字段名称的聚合管道

Mongodb aggregate pipeline for matching a reference model's field name of a sub document in a collection

我有两个集合,一个是 Product,另一个是 Stores

prouduct1 = {
name: "chair",
code: 034,
};

product2 = {
name: "table",
code: 035,
};

在 material 条目期间,商店模型更新为以下架构

goodsReceipt = {

invoicenumber: 2,
products: [
    { product: "ObjectId(product1)", qty: 15 },
    { product: "ObjectId(product2)", qty: 20 },    
 ],

};

现在,我想遍历整个商店的注册和匹配的产品 1 id,然后找出其所有数量的总和。

您可以使用以下聚合

import mongoose from "mongoose";

db.stores.aggregate([
  { $match: { "products.product": mongoose.Types.ObjectId(productId) }},
  { $unwind: "$products" },
  { $match: { "products.product": mongoose.Types.ObjectId(productId) }},
  { $group: {
    _id: null,
    qty: { $sum: "$products.qty" }
  }}
])