简体   繁体   中英

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. Ie 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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM