Search⌘ K
AI Features

Solution: Merging Documents

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.

  • Lines 9–13: The $merge stage writes the filtered documents into a new or existing collection called "FurnitureProducts".

    • whenMatched: "keepExisting": If a document with the same _id ...