Skip to main content

Subset Pattern

  • a book have N reviews
  • only embed 3 reviews to the book

Code Summary: Subset Pattern To apply the Subset pattern to the documents in our bookstore app, we ran the following aggregation pipeline:

use("bookstore");
const copyReviews = [
  {
    // TODO: Specify the $reviews array to unwind.
    $unwind: { path: "$reviews" },
  },
  {
    $set: {
      "reviews.book_id": "$_id",
    },
  },
  {
    // TODO: Specify the $reviews array as the newRoot
    // in the $replaceRoot stage.
    $replaceRoot: {
      newRoot: "$reviews",
    },
  },
  {
    $out: "reviews_66da32c8",
  },
];

print("Running the aggregation pipeline");

db.books_66da32c8.aggregate(copyReviews);

print("aggregation operation completed");

Next, we defined a clean up pipeline to ensure the reviews array in the book documents only includes three reviews:

use("bookstore");
const cleanupReviews = [
  {
    $set: {
      reviews: {
        // TODO: Specify the $reviews array and a size of 3 
        // in the $slice array
        $slice: [ "$reviews", 3 ],
      },
    },
  },
];

print("Updating the reviews array")
var res = db.books_ab11cd62.updateMany({}, cleanupReviews);
print(res)

Finally, we ran this pipeline for the books collection with the updateMany method:

db.books.updateMany({}, update_reviews_array_pipeline);