dynamically updating and retrieving data in mongodb

This is a time-honored data design: products and reviews. A good, simple, scalable way to approach it is with two collections: product and reviews. The product collection contains all details about a product and carries the product ID (pid):

{pid: "ABC123", name: "TV", manu: "Sony", ...}
{pid: "G765", name: "Fridge", manu: "Whirlpool", ...}

The reviews collection is an ever-growing list of pid, timestamp, and review information.

{pid: "G765", ts: ISODate("2020-03-04), author: "A1", review: "Great", rating: 4}
{pid: "G765", ts: ISODate("2020-03-05), author: "A2", review: "Good", rating: 3}
{pid: "G765", ts: ISODate("2020-03-06), author: "A3", review: "Awesome", rating: 5}

If you’re thinking this sounds very relational, that’s because it is and it is a good design pattern. It answers the OP questions easily: 1- How do I insert the products individually without overwriting everything within products:{}. ANSWER: You simply add a new product doc with a new pid to the product collection.

2- How do I update the review or rating value within a certain product. ANSWER Not sure you want to do that; you probably want to accumulate reviews over time. But since each review is a separate doc (with a separate _id) you can easily do this:

db.reviews.update({_id:targetID},{$set: {review:"new text"}});

3- How do I get information about that product because I cannot do something like doc.products.product.id.review, product.id is the only information I have about the product. Easy:

db.product.find({pid:"ABC123"})
or
db.product.find({name:"TV"})

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top