catJam
catJam

Reputation: 230

From records display only the one with highest price

I have a vanilla js app with express on the backend and mongoDB. Basically a restaurant builder, each customer can reserve a table with form. The inputs are name, select box with available table s and BID price. The bid means that the customer with highest bid for the table will win the table the other ones will lose it.

How can I fetch only the customer with highest bid for the x table ?

For example if I have 3 customers in below snippet booked in for tableID "2" how can I only get the one with the highest bid ?

Let's imagine a payload like this:

const bookings = [
  {
    customerName: 'Joe',
    bidValue: 178, // for example in $ - dollars
    tableID: 2
  },
  {
    customerName: 'Frank',
    bidValue: 212, // for example in $ - dollars
    tableID: 2
  },
  {
    customerName: 'Martin',
    bidValue: 123, // for example in $ - dollars
    tableID: 2
  },
  {
    customerName: 'John',
    bidValue: 15, // for example in $ - dollars
    tableID: 1
  },
  {
    customerName: 'Gino',
    bidValue: 87, // for example in $ - dollars
    tableID: 1
  },
  {
    customerName: 'Patrick',
    bidValue: 23, // for example in $ - dollars
    tableID: 3
  },
];

Upvotes: 1

Views: 112

Answers (2)

user14187399
user14187399

Reputation:

You should use the sort function (1 Ascending -1 descending).

db.bookings.find().sort( { "bidValue": 1 } )

Upvotes: 1

J.F.
J.F.

Reputation: 15215

To get only the highest value you need to use $sort and $limit in this way:

  • First $match to get the table which you can get the highest bid.
  • Then $sort descending to get the highest value at first position
  • And $limit to output only first value (i.e. the highest)
db.collection.aggregate(
{"$match": {"tableID": 2}},
{"$sort": {"bidValue": -1}},
{"$limit": 1})

Example here

And, to get the highest value for each table you also need $group stage into the aggregation pipeline.

In this case, the query is a little bit different.

  • First $sort to get the highest value on top and then
  • $group by tableId.
  • And use $first to get the max value because are sort, then, the first element will be the desired one.
{
  "$sort": {"bidValue": -1}
},
{
  "$group": {
    "_id": "$tableID",
    "customerName": {"$first": "$customerName"},
    "bidValue": {"$first": "$bidValue"}
  }
})

Example here

Upvotes: 1

Related Questions