首页 > 解决方案 > SQL 'UNION ALL' 类似 MongoDB 中的实现

问题描述

有两个集合:

销售量

{
  "_id" : ObjectId("5ba0bfb8d1acdc0de716e839"),
  "invoiceNumber" : 1,
  "saleDate" : ISODate("2018-09-01T00:00:00.000Z"),
  "totalTaxAmount" : 613,
  "subTotalAmount" : 2000,
  "totalAmount" : 2613,
  "balance" : 2613,
  "financialYear" : "2018-2019",
  "modeOfPayment" : "Digital Transfer",
  "customerName": "Acme Inc"
}

交易

{
  "_id" : ObjectId("5bbb4e131fb8af0dc645212d"),
  "transactionNumber" : 1    
  "transactionDate" : ISODate("2018-09-03T00:00:00.000Z"),
  "transactionType" : "Income",
  "partyName" : "Acme Inc",
  "transactionMode" : "Digital Transfer",
  "amount" : 2613,
  "paidItems" : [ 
      {
          "orderId" : "5b90a7d62bb5a21be4ff97e3",
          "invoiceNumber" : "1",
          "orderType" : "sale",
          "totalAmount" : 2613,
          "balance" : 613,
          "payingAmount" : 2000
      }
   ]
}

我需要在按日期排序的两个日期(即 saleDate、transactionDate)之间检索销售和交易作为特定方(即 customerName、partyName)的“标题”;如下:

[
  {
    "date": ISODate("2018-09-01T00:00:00.000Z"),
    "heading": "Sale",
    "particulars": "Invoice # 1",
    "amount": 2613
  },
  {
    "date": ISODate("2018-09-03T00:00:00.000Z"),
    "heading": "Payment by Digital Transfer",
    "particulars": "Transaction # 1",
    "amount": 2000
  }
]

我研究并尝试了aggregation$lookup但它没有返回所需的内容。

从 SQL 切换到 MongoDB。在 SQL 中,以下查询工作正常:

select sale_date as dated, 'Sale' as heading, 'Invoice # ' + 
convert(varchar(12),invoice_number) as particulars, 
convert(varchar(12), total) as amount, 
from sales where sale_date between @from_date AND @to_date AND 
customer_name=@customer_name
UNION ALL
select transaction_date as dated, 'Payment by ' + transaction_mode as 
heading, 'Transaction # ' + convert(varchar(12), transaction_id) as 
particulars, convert(varchar(12), amount) as amount from transactions 
where transaction_date between @from_date AND @to_date AND 
party_name=@customer_name
order by dated DESC

在 MongoDB 社区中提交了一个功能请求,但它“未解决”。

我想知道在 mongoShell 或 MongoDB 驱动程序(mongoose / JS)中有什么办法。使用当前稳定版本的 MongoDB、nodejs、express 和 mongoose。谢谢!

标签: node.jsmongodbmongodb-queryaggregation-framework

解决方案


您可以尝试以下聚合

db.sales.aggregate([
  { "$limit": 1 },
  { "$facet": {
    "collection1": [
      { "$limit": 1 },
      { "$lookup": {
        "from": "sales",
        "pipeline": [
          { "$match": {
            "date": { "$gte": ISODate("2018-09-01"), "$lte": ISODate("2018-09-10") },
            "customer.name": customerName
          }},
          { "$project": {
            "_id":0, "dated": "$saleDate", "heading": "Sale", "particulars": "$invoiceNumber",
            "amount": "$totalAmount", "modeOfPayment": null
          }}
        ],
        "as": "collection1"
      }}
    ],
    "collection2": [
      { "$limit": 1 },
      { "$lookup": {
        "from": "transactions",
        "pipeline": [
          { "$match": {
            "transactionDate": { "$gte": ISODate("2018-09-01"), "$lte": ISODate("2018-09-10") },
            "userId": userId, "partyName": customerName
          }},
          { "$project": {
            "_id":0, "dated": "$transactionDate", "heading": "Payment","particulars": "$transactionNumber",
            "amount": "$amount", "paymentMode": "$transactionMode"
          }}
        ],
        "as": "collection2"
      }}
    ]
  }},
  { "$project": {
    "data": {
      "$concatArrays": [
        { "$arrayElemAt": ["$collection1.collection1", 0] },
        { "$arrayElemAt": ["$collection2.collection2", 0] },
      ]
    }
  }},
  { "$unwind": "$data" },
  { "$replaceRoot": { "newRoot": "$data" } },
  { "$sort": { "dated": -1 }}
])

推荐阅读