skip to Main Content

The context is group discounts where a group of people between 4-7 would get a 5% discount and a group between 8-12 would get 10%. When I query with 5 people. I get [] back using the following query:

  await Discount.find({ amount: { $gte:5, $lte: 8 } })
    .then((discounts) => {
      console.log(discounts);
    })
    .catch(next);

But I was trying to get the following object:

[
  {
    name: '4+ Group Size',
    amount: 4,
  },
  {
    name: '8 Group Size',
    amount: 8,
  }
]

How do I query BETWEEN two values?

2

Answers


  1. For a db like this:

    [
      {
        name: "0 Group Size",
        amountOfPeople: 0,
        discount: 0
      },
      {
        name: "4+ Group Size",
        amountOfPeople: 4,
        discount: 5
      },
      {
        name: "8 Group Size",
        amountOfPeople: 8,
        discount: 10
      }
    ]
    

    You can use a query:

    db.collection.find({ amountOfPeople: {$lte: numberOfPeopleInGroup}})
    .sort({amountOfPeople: -1}).limit(1)
    

    To get the relevant discount per amount of people in the group

    See how the logic works on the playground example using aggregation pipeline only because of the playground limitations.

    Login or Signup to reply.
  2. You can also use the $and operator

    await Discount.find( { $and:[ {amount:{$gte:4}}, {amount:{$lte:8}} ] } )
      .then((discounts) => {
        console.log(discounts);
      })
      .catch(next);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search