Solution: Merging Documents
We'll cover the following...
Query
// Picking Furniture products from products collectiondb.products.aggregate([{$match: {category: "Furniture"}},{$merge: {into: "furniture", // Adding matched products to a new collectionwhenMatched: "keepExisting",whenNotMatched: "insert"}}]),// Deleting Furniture products from the original products collectiondb.products.deleteMany({category: "Furniture"}),// Fetch documents from the FurnitureProducts collectiondb.furniture.find()
The explanation of the query is given below:
Line 2: This starts an aggregation pipeline on the
productscollection.Lines 4–6: The
$matchstage filters documents where thecategoryfield is"Furniture". Only products under the Furniture category will move to the next stage.Lines 9–13: The ...