# MongoDB UNION ALL 實現 ### Version 4.4 or later 可使用 `$unionWith` ```mongodb= db.suppliers.insertMany([ { _id: 1, supplier: "Aardvark and Sons", state: "Texas" }, { _id: 2, supplier: "Bears Run Amok.", state: "Colorado"}, { _id: 3, supplier: "Squid Mark Inc. ", state: "Rhode Island" }, ]) db.warehouses.insertMany([ { _id: 1, warehouse: "A", region: "West", state: "California" }, { _id: 2, warehouse: "B", region: "Central", state: "Colorado"}, { _id: 3, warehouse: "C", region: "East", state: "Florida" }, ]) db.suppliers.aggregate([ { $project: { state: 1, _id: 0 } }, { $unionWith: { coll: "warehouses", pipeline: [ { $project: { state: 1, _id: 0 } } ]} } ]) ``` ### Before version 4.4 使用 `$lookup` 搭配 `$group.$push`, `$concatArrays`, `$unwind`, `$replaceRoot` ```mongodb 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 }) ``` 參考自: [MongoDB Docs > $unionWith (aggregation)](https://www.mongodb.com/docs/v6.0/reference/operator/aggregation/unionWith/) [stackoverflow > SQL 'UNION ALL' like implementation in MongoDB](https://stackoverflow.com/a/52728587/11563389) ###### tags: `MongoDB`