MongoDB 3.6-如何将一个集合中的匹配项追加到另一个集合中?

时间:2019-01-14 04:01:47

标签: mongodb mongodb-query aggregation-framework

集合1-发票行 集合2-税额线

案例:1个发票行可以与多个税项相关联。

如何获取1条发票行记录,以在其上附加每个匹配的税项?

发票行和税项之间有一个匹配键。现在,我的汇总正在创建2个结果发票行记录(重复的发票行与匹配的税款行),而不是将匹配的税收行附加到单个发票行记录中。

Graphic depiction of current collections and document examples.


发票行示例文档...

{ 
    "UniqueID" : NumberInt(3851963), 
    "InvNum" : NumberInt(35602582), 
    "Location" : "035", 
    "InvoiceDate" : ISODate("2017-07-15T12:00:00.000+0000"), 
    "LINEITEM" : NumberInt(1), 
    "CUSTID" : "001595", 
    "DEPTID" : "035360", 
    "PRODID" : "003600", 
    "ProdDesc" : "MISC MERCHANDISE", 
 }

税收行示例文档(需要同时将其附加到上面的发票行)... 税项凭证1

{ 
    "InvoiceDate" : "7/15/2017 12:00:00 AM", 
    "Location" : "035", 
    "InvNum" : NumberInt(35602582), 
    "LineItem" : NumberInt(1), 
    "UniqueID" : NumberInt(1), 
    "taxCode" : "mu48", 
    "taxrate" : NumberInt(2), 
}

税收行凭证2

{ 
    "InvoiceDate" : "7/15/2017 12:00:00 AM", 
    "Location" : "035", 
    "InvNum" : NumberInt(35602582), 
    "LineItem" : NumberInt(1), 
    "UniqueID" : NumberInt(1), 
    "taxCode" : "mu48", 
    "taxrate" : NumberInt(2), 
}

1 个答案:

答案 0 :(得分:1)

您可以在aggregation以下与mongodb 3.6 及更高版本

一起使用
db.invoice.aggregate([
  { "$lookup": {
    "from": "tax",
    "let": { "invNum": "$InvNum", "lINEITEM": "$LINEITEM" },
    "pipeline": [
      { "$match": {
        "$expr": {
          "$and": [
            { "$eq": ["$InvNum", "$$invNum"] },
            { "$eq": ["$LineItem", "$$lINEITEM"] }
          ]
        }
      }}
    ],
    "as": "taxes"
  }}
])