Home > Net >  Find an item within an array in a collection with the highest score overall and return with that sco
Find an item within an array in a collection with the highest score overall and return with that sco

Time:09-03

Schema:

const restaurantSchema = new mongoose.Schema({
  address: {
    building: String,
    coord: [Number, Number],
    street: String,
    zipcode: String,
  },
  borough: String,
  cuisine: String,
  grades: [{ date: Date, grade: String, score: Number }],
  name: String,
  restaurant_id: String,
});

I am trying to find a restaurant with the highest grades.score and return what that score is.

What I've tried doing:

Restaurant.find({}, { "grades.score": 1, _id: 0 }).sort({ "grades.score": -1 }).limit(1).exec((err, docs) => {
    if (err) {
        console.log(err);
    } else {
        console.log(docs);
    }
});

What it returns:

[
  {
    grades: [ [Object], [Object], [Object], [Object], [Object], [Object] ]
  }
]

What I want:

[
   {
      score: 131
   }
]

CodePudding user response:

Query

  • you can use the $max aggregate operator that works as accumulator and on arrays like here
  • this is for the local(inside the document array) max-score if you want for the global(in all the collection) you can sort desc by max-score and $limit 1

Playmongo

aggregate(
[{"$project": {"_id": 0, "max-score": {"$max": "$grades.score"}}}])
  • Related