I have a database schema like this:
var User = new mongoose.Schema({
...
points:{
type: Number
},
extraPoints:{
type: Number
},
...
})
Ok, when I want to sort the database I want to have a filed that sums the two fields like this:
var newFiled = (points*50 + extraPoints);
so when I sort the database I'd do something like this:
model.User.find({}).sort(newFiled).exec();
I've checked out the aggregate but I don't know how to sort it when it's aggregated.
Thanx for help :)
In mongodb aggregation, this can be achieved through the $project
operator. The newField
is added via the $project
operator pipeline stage with the $add
arithmetic operator which adds the two fields. The sorting is done through the $sort
pipeline step:
var pipeline = [
{
"$project": {
"points": 1,
"extraPoints": 1,
"newField": { "$add": [ "$points", "$extraPoints" ] }
},
{
"$sort": { "newField": 1 }
}
];
model.User.aggregate(pipeline, function (err, res) {
if (err) return handleError(err);
console.log(res);
});
// Or use the aggregation pipeline builder.
model.User.aggregate()
.project({
"points": 1,
"extraPoints": 1,
"newField": { "$add": [ "$points", "$extraPoints" ] }
})
.sort("newField")
.exec(function (err, res) {
if (err) return handleError(err);
console.log(res);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With