MongoDB $and use cases

Viewed 33

What is the use cases of $and operator.

Looks like those are same

    this.matchModel.find({
      color: 'red',
      size: 'large'
    })

    this.matchModel.find({
      $and: [
        {
          color: 'red'
        },
        {
          size: 'large'
        }
      ]
    })

Aren't those same?

1 Answers

Yes, they mean the same, but they do make more sense if you want to combine it with other operators like $or. Consider the logic below, it makes code more readable too.

this.matchModel.find({
  $or: [
    {
      $and: [
        {
          size: { $gt: 1}
        },
        {
          size: { $lt: 5}
        }
      ]
    },
    {
      color: 'red'
    }
  ]
})

Here the logic is (size greater than 1 and less than 5) OR (color is red)

Related