Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
   }
]

>Solution :

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"}}}])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading