Search⌘ K
AI Features

Solution: Merging Documents

The aggregation pipeline in MongoDB allows for multi-stage document processing, enabling filtering, grouping, and exporting of data. In this solution, documents from the "products" collection are filtered to include only those in the "Furniture" category, which are then merged into a new collection called "FurnitureProducts." Existing documents are preserved, while new ones are inserted. Following this, the original "products" collection is cleaned by removing the transferred documents. This method is effective for archiving and organizing data.

We'll cover the following...
Query
// Picking Furniture products from products collection
db.products.aggregate([
{
$match: {
category: "Furniture"
}
},
{
$merge: {
into: "furniture", // Adding matched products to a new collection
whenMatched: "keepExisting",
whenNotMatched: "insert"
}
}
]),
// Deleting Furniture products from the original products collection
db.products.deleteMany({
category: "Furniture"
}),
// Fetch documents from the FurnitureProducts collection
db.furniture.find()

The explanation of the query is given below:

  • Line 2: This starts an aggregation pipeline on the products collection.

  • Lines 4–6: The $match stage filters documents where the category field is "Furniture". Only products under the Furniture category will move to the next stage. ...