如何从其他文档关系中对交易子文档 mongodb 中的项目求和

How to sum item in transaction subdocument mongodb from other document relationship

我是 mongodb 的新手,尝试像下面这样设计小项目和文档

产品

[
    {
      _id:ObjectId('60d87d6fafd7a1377c03b2e6'),
      productName:"noodles instant",
      description:"lorem ipsum ... ... ...."
    },
    {
      _id:ObjectId('60d87d6fafd7a1377c03b2e7'),
      productName:"Sandal",
      description:"lorem ipsum ... ... ...."
    }
]

我的交易文档结构如下 交易

   [
    { 
       _id:ObjectId('60d8781031308dbf565eaaa8'),
       trasactionSerial:"TRS20210000001",
       transactionDate:2021-06-27T13:30:23.369+00:00,
       productInTransactions:[
          {
            _id:ObjectId('60d8781031308dbf565eaab9'),
            productId:ObjectId('60d87d6fafd7a1377c03b2e6'),
            qty:1500
          },
          {
            _id:ObjectId('60d8781031308dbf565eaa47'),
            productId:ObjectId('60d87d6fafd7a1377c03b2e7'),
            qty:200
          }
          
       ]
    },
    { 
       _id:ObjectId('60d8781031308dbf565eaab7'),
       trasactionSerial:"TRS20210000002",
       transactionDate:2021-06-27T13:32:23.369+00:00,
       productInTransactions:[
          {
            _id:ObjectId('60d8781031308dbf565eaab9'),
            productId:ObjectId('60d87d6fafd7a1377c03b2e6'),
            qty:100
          },
          {
            _id:ObjectId('60d8781031308dbf565eaa47'),
            productId:ObjectId('60d87d6fafd7a1377c03b2e7'),
            qty:300
          }
          
       ]
    }   
   ]

从交易中我希望在 transactionDate 字段

的同一日期得到如下结果

结果


   [
     {
       _id:ObjectId('60d87d6fafd7a1377c03b2e6'),
       productName:"noodles instant",
       qtyInTransaction:1600
     },
     {
       _id:ObjectId('60d87d6fafd7a1377c03b2e7'),  
       productName:"Sandal",
       qtyInTransaction:500
     },
   ]

sorry maybe my English is poor to elaborate it

感谢您的任何反馈和帮助

使用管道选项中包含 $group$lookup 阶段。

db.products.aggregate([
  {
    "$lookup": {
      "from": "transactions",
      "let": {
        "pId": "$_id"
      },
      "pipeline": [
        {
          "$unwind": "$productInTransactions"
        },
        {
          "$match": {
            "$expr": {
              "$eq": [
                "$productInTransactions.productId",
                "$$pId"
              ]
            },
          },
        },
        {
          "$group": {
            "_id": "$$pId",
            "qtyInTransaction": {
              "$sum": "$productInTransactions.qty"
            }
          },
        },  
      ],
      "as": "matchedTransactions"
    }
  },
  {
    "$project": {
      "_id": 1,
      "description": 1,
      "qtyInTransaction": {
        "$arrayElemAt": [
          "$matchedTransactions.qtyInTransaction",
          0
        ]
      }
    },
  },
])

Mongo Playground Sample Execution