Reputation: 230
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
Reputation:
You should use the sort function (1 Ascending -1 descending).
db.bookings.find().sort( { "bidValue": 1 } )
Upvotes: 1
Reputation: 15215
To get only the highest value you need to use $sort
and $limit
in this way:
$match
to get the table which you can get the highest bid.$sort
descending to get the highest value at first position$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.
$sort
to get the highest value on top and then$group
by tableId
.$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