SQL 'UNION ALL' like implementation in MongoDB

前端 未结 3 1912
慢半拍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:29

    Disclaimer: The technique presented below is not exactly advisable. ;) This is true in particular when dealing with big collections. However, it can be used to achieve the identical effect as a SQL UNION ALL from MongoDB v3.6 onwards.

    Given a collection first and a collection second:

    db.first.aggregate([{
        $group: { // create an array to hold all documents of the first collection
            "_id": null,
            "first": {
                $push: "$$ROOT"
            }
        }
    }, {
        $lookup: { // perform some kind of ridiculous lookup which will return all documents from the second collection in an array
            from: "second",
            let: { /* we do not need any variables */ },
            pipeline: [ { $match: { /* this filter will match every document */ } } ],
            as: "second"
        }
    }, {
        $project: {
            "all": { $concatArrays: [ "$first", "$second" ] } // merge the two collections
        }
    }, {
        $unwind: "$all" // flatten the resulting array
    }, {
        $replaceRoot: { "newRoot": "$all" } // move content of "all" field all the way up 
    }], {
        allowDiskUse: true // make sure we do not run into memory issues
    })
    

提交回复
热议问题