How to Sort in Mongoose

Sorting in mongoose

See here for some decent answers on sorting and
here is some good official docs on mongoose async/await

You should use .exec() with await for better stack traces, the sort can take these values: asc, desc, ascending, descending, 1, and -1.

try {
let properties = await Property.find(query).sort({"minimumPrice": -1}).exec()
} catch (err) {
console.log(err)
}

This is all assuming your query is correct and is retrieving documents to be sorted.

UPDATE

I went through your whole situation and created a test using what you provided.

const mongoose = require("mongoose");
var Schema = mongoose.Schema;
var propertySchema = new Schema({
name: String,
minimumPrice: Number
});
var Property = mongoose.model('Property', propertySchema);

//Testing
(async function() {
try {
//connect to mongo
await mongoose.connect('mongodb://localhost:27017/testing', { useNewUrlParser: true, useUnifiedTopology: true });

//First, delete all properties
await Property.deleteMany({}).exec();

let properties = [];
//Insert 5 properties
for (var i = 1; i < 6; i++) {
properties.push({ name: "property" + i, minimumPrice: Math.round(Math.random() * 10000) });
}

//Insert all our random properties
await Property.create(properties);

console.log(properties);

//Now, retrieve all our properties
let sortedProperties = await Property.find({}).sort({ minimumPrice: -1 }).exec();

console.log("sorted", sortedProperties);
} catch (err) {
console.log(err);
}
})();

Database Input:

[                                           
{ name: 'property1', minimumPrice: 3846 },
{ name: 'property2', minimumPrice: 7910 },
{ name: 'property3', minimumPrice: 7234 },
{ name: 'property4', minimumPrice: 4444 },
{ name: 'property5', minimumPrice: 6366 }
]

Sorted Output:

[
{
name: 'property2',
minimumPrice: 7910
},
{
name: 'property3',
minimumPrice: 7234
},
{
name: 'property5',
minimumPrice: 6366
},
{
name: 'property4',
minimumPrice: 4444,
},
{
name: 'property1',
minimumPrice: 3846
}
]

You can see the properties come back sorted. Which leads me to assume, somewhere you've inserted your minimumPrice as a string.

In Mongoose, how do I sort by date? (node.js)

Sorting in Mongoose has evolved over the releases such that some of these answers are no longer valid. As of the 4.1.x release of Mongoose, a descending sort on the date field can be done in any of the following ways:

    Room.find({}).sort('-date').exec((err, docs) => { ... });
Room.find({}).sort({date: -1}).exec((err, docs) => { ... });
Room.find({}).sort({date: 'desc'}).exec((err, docs) => { ... });
Room.find({}).sort({date: 'descending'}).exec((err, docs) => { ... });
Room.find({}).sort([['date', -1]]).exec((err, docs) => { ... });
Room.find({}, null, {sort: '-date'}, (err, docs) => { ... });
Room.find({}, null, {sort: {date: -1}}, (err, docs) => { ... });

For an ascending sort, omit the - prefix on the string version or use values of 1, asc, or ascending.

Mongoose Query To Sort Main Document & SubDocument by particular field

Currently sort is not possible directly inside array objects,

You can do either 2 options,

  • if you are getting data from lookup then use lookup with pipeline it will allow to use $sort pipeline within match documents
  • $unwind the array => $sort it => again $group it into array, Refer SO Answer

here you are using $lookup, instead of simple lookup you can use "$lookup with pipeline".

  {
$lookup: {
from: "tags",
as: "tags",
let: { id: "$_id" },
pipeline: [
{
$match: {
$expr: { $eq: ["$$id", "$tag_type"] }
}
},
{
$sort: { order: -1 }
}
]
}
},

Playground


Second possible solution: Playground

Mongoose sorting by createdAt

sort() can't take arrays it either takes string or an object

const posts = await Post.find().sort({createdAt: 1});

also you can use " asc "," ascending " instead of 1.

How to sort in mongoose by specific order?

I solved it by adding weight of Category. Now my model is like this:

const schema = new Schema({
Name: { type: String },
Category: { type: String },
CategoryWeight: { type: Number },
Price: { type: Number }
})

And I sorting like this:

const products = await Product.find().sort('-CategoryWeight')

Mongoose Sort by elements in array

You can add a temporary key that holds 1 if the key exists
and 0 if the key doesn't exist, sort in descending order based on this temporary key.

db.collection.aggregate([
{
"$addFields": {
"searchElemExists": {
"$cond": {
"if": {
"$in": [
"1", // <-- Value you want to be sorted based on existance
"$favorites"
]
},
"then": 1,
"else": 0
}
}
},

},
{
"$sort": {
"searchElemExists": -1
}
},
{
"$project": {
"searchElemExists": 0,
},
},
])

Playground Execution of Sample Data

how to sort elements on the basis of populated object in mongodb (mongoose)

You can't sort on virtual fields or populated fields as those fields are only present in your app objects (Mongoose model instances) but the sort is executed within MongoDB.

Reference:

  • Sort query with populated field
  • The correct syntax for sorting mongoose 3.x populated document
  • Mongoose, sort query by populated field

You can also use aggregate on MongoDB.

db.getCollection('user').aggregate([
{ $lookup: { from: "wallet", localField: "wallet_id", foreignField: "_id", as: "wallet" }},
{ $unwind: "$wallet" },
{ $sort: {'wallet.amount': 1}}
]);


Related Topics



Leave a reply



Submit