【问题标题】:Mongodb aggregate pipeline for matching a reference model's field name of a sub document in a collection用于匹配集合中子文档的参考模型字段名称的MongoDB聚合管道
【发布时间】:2020-08-06 06:45:39
【问题描述】:

我有两个系列,一个是 Product,另一个是 Stores

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

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

在材料输入期间,Stores 模型使用以下架构更新

goodsReceipt = {

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

};

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

【问题讨论】:

    标签: node.js mongodb mongodb-query aggregation-framework mongoose-populate


    【解决方案1】:

    你可以使用下面的聚合

    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" }
      }}
    ])
    

    【讨论】:

      猜你喜欢
      • 2014-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-05
      • 2015-05-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-14
      相关资源
      最近更新 更多