SQL 'UNION ALL' like implementation in MongoDB

前端 未结 3 1902
慢半拍i
慢半拍i 2021-01-23 01:53

There are two collections:

Sales

{
  \"_id\" : ObjectId(\"5ba0bfb8d1acdc0de716e839\"),
  \"invoiceNumber\" : 1,
  \"saleDate\" : ISODate(\"2018-09-01T00:         


        
3条回答
  •  灰色年华
    2021-01-23 02:22

    You can try below aggregation

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

提交回复
热议问题