BDS456B Program 4

4. Create and demonstrate how projection operators ($, $elematch and $slice) would be used in the MongoDB.

use retailDB
db.Products.insertMany([
  {
    name: "Laptop",
    brand: "BrandA",
    features: [
      { name: "Processor", value: "Intel i7" },
      { name: "RAM", value: "16GB" },
      { name: "Storage", value: "512GB SSD" }
    ],
    reviews: [
      { user: "Alice", rating: 5, comment: "Excellent!" },
      { user: "Bob", rating: 4, comment: "Very good" },
      { user: "Charlie", rating: 3, comment: "Average" }
    ]
  },
  {
    name: "Smartphone",
    brand: "BrandB",
    features: [
      { name: "Processor", value: "Snapdragon 888" },
      { name: "RAM", value: "8GB" },
      { name: "Storage", value: "256GB" }
    ],
    reviews: [
      { user: "Dave", rating: 4, comment: "Good phone" },
      { user: "Eve", rating: 2, comment: "Not satisfied" }
    ]
  }
])

Use Projection Operators:

1. $ Projection Operator: Find the product named “Laptop” and project the review from the user “Alice”.

db.Products.find(
  { name: "Laptop", "reviews.user": "Alice" },
  { "reviews.$": 1 }
).pretty()

OUTPUT:

[
  {
    _id: ObjectId('666c2f237d3bfa1feacdce05'),
    reviews: [ { user: 'Alice', rating: 5, comment: 'Excellent!' } ]
  }
]

2. $elemMatch Projection Operator: Find the product named “Laptop” and project the review where the rating is greater than 4.

db.Products.find(
  { name: "Laptop" },
  { reviews: { $elemMatch: { rating: { $gt: 4 } } } }
).pretty()

OUTPUT:

[
  {
    _id: ObjectId('666c2f237d3bfa1feacdce05'),
    reviews: [ { user: 'Alice', rating: 5, comment: 'Excellent!' } ]
  }
]

3. $slice Projection Operator: Find the product named “Smartphone” and project the first review.

db.Products.find(
  { name: "Smartphone" },
  { reviews: { $slice: 1 } }
).pretty()

OUTPUT:

[
  {
    _id: ObjectId('666c2f237d3bfa1feacdce06'),
    name: 'Smartphone',
    brand: 'BrandB',
    features: [
      { name: 'Processor', value: 'Snapdragon 888' },
      { name: 'RAM', value: '8GB' },
      { name: 'Storage', value: '256GB' }
    ],
    reviews: [ { user: 'Dave', rating: 4, comment: 'Good phone' } ]
  }
]

Leave a Reply

Your email address will not be published. Required fields are marked *