Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

180
Views
Sort on values in array with mongoose

I got a schema for products. I want to be able to query them and sort on discount. The price is represented with an array called price, the latest element is the newest value. I.e I want the product with the highest discount first in the query.

Schema:

const mongoose = require('mongoose');

const ProductsSchema = new mongoose.Schema(
  {
    productName: {
      type: String,
    },
    price: [
      {
        date: {
          type: String,
        },
        value: {
          type: Number,
        },
      },
    ],
  },
  { collection: 'products' }
);
const products = mongoose.model('products', ProductsSchema);
module.exports = products;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Query1

  • adds a field called discount
  • discount= priceN-princeN-1 (the difference between the last 2 prices), here is like the latest discount
  • if the product has < 2 prices discount = 0

Test code here

aggregate(
[{"$set":
  {"discount":
   {"$cond": 
    [{"$lte":[{"$size":"$price"}, 1]}, 0,
     {"$subtract":
      [{"$last":"$price.value"},
       {"$arrayElemAt":
        ["$price.value", {"$subtract":
                          [{"$size":"$price"}, 2]}]}]}]}}},
 {"$sort":{"discount":-1}}])

Query2

  • same like above
  • discount = lastPrice - minPrice

*you can replace $last with $max to get the max discount of all time

aggregate(
[{"$set":
  {"discount":
   {"$cond":
    [{"$lte":[{"$size":"$price"}, 1]}, 0,
     {"$subtract":
      [{"$last":"$price.value"}, {"$min":"$price.value"}]}]}}},
 {"$sort":{"discount":-1}}])
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!