Bug related to $let

Found a bug for $let stage.

db.products.insertMany([
    {
      _id: 1,
      name: "UltraHD TV 55''",
      price: 1200.00,
      rating: [5, 4, 5, 3, 4],
      stocks: {
        "New York": 20,
        "Los Angeles": 15,
        "Chicago": 10,
        "Houston": 5,
        "Phoenix": 8
      }
    },
    {
      _id: 2,
      name: "Smartwatch 4",
      price: 299.99,
      rating: [4, 5, 4, 4, 5],
      stocks: {
        "New York": 25,
        "Los Angeles": 20,
        "Chicago": 15,
        "Houston": 10,
        "Phoenix": 12
      }
    },
    {
      _id: 3,
      name: "Wireless Earbuds",
      price: 129.99,
      rating: [4, 3, 4, 5, 4],
      stocks: {
        "New York": 30,
        "Los Angeles": 25,
        "Chicago": 20,
        "Houston": 15,
        "Phoenix": 18
      }
    },
    {
      _id: 4,
      name: "Gaming Laptop",
      price: 1500.00,
      rating: [5, 5, 5, 4, 5],
      stocks: {
        "New York": 10,
        "Los Angeles": 8,
        "Chicago": 12,
        "Houston": 5,
        "Phoenix": 4
      }
    },
    {
      _id: 5,
      name: "Tablet 8''",
      price: 450.00,
      rating: [4, 4, 3, 4, 4],
      stocks: {
        "New York": 40,
        "Los Angeles": 35,
        "Chicago": 30,
        "Houston": 25,
        "Phoenix": 20
      }
    }
  ]);

db.products.aggregate([
  {
    '$project': {
      name: 1,
      updateNeeded: {
        '$let': {
          vars: {
            avgRating: {
              '$avg': '$ratings'
            }
          },
          in: {
            '$lt': [
              '$$avgRating',
              3
            ]
          }
        }
      }
    }
  },
  {
    '$sort': {
      _id: 1
    }
  }
])

Output - 
[
  {
    _id: 1,
    name: "UltraHD TV 55''",
    updateNeeded: true
  },
  {
    _id: 2,
    name: 'Smartwatch 4',
    updateNeeded: true
  },
  {
    _id: 3,
    name: 'Wireless Earbuds',
    updateNeeded: true
  },
  {
    _id: 4,
    name: 'Gaming Laptop',
    updateNeeded: true
  },
  {
    _id: 5,
    name: "Tablet 8''",
    updateNeeded: true
  }
]

The output must be ‘false’ for all the docs

Hi Abhishek,

There is no bug in $let stage, it’s just a simple typo in your pipeline.
In the documents you have the field as $rating but in the $let stage you mentioned $ratings which resulted in the average as null subsequently which is lesser than 3 so thats why in the output every document has the value of updateNeeded as true.

2 Likes