Ethan Wu Ethan Wu -4 years ago 126
Node.js Question

Moongoose sort by parseFloat(String)

I want sort my query result by the

Float value
. But the value stored in mongodb is type
,Can I parse the
and sort it dynamically? Just like complex sort.

The following are parts of my schema and sort code:


var ScenicSpotSchema = new Schema({
detail_info: {
overall_rating: String,

Sort function:

ScenicSpot.find({'name': new RegExp(req.query.keyword)}, )
.skip(pageSize * pageNumber)
.exec(function (err, scenicSpots) {
if (err) {
} else {
callback(null, scenicSpots);

Any kind of help and advice is appreciated. :)

Answer Source

.sort mongoose do not support converting data type. see:

It only accept column names and order.

There are two path to acheive your goal:

  1. use mapreduce in mongo, first convert type, and the sort
  2. retrieve all data from database, and sort it in your node.js program.

But both are terrible and ugly

if you wanna sort a String column but parse it as Float. This action would scan all data in that collection, and can not use index. It's very very slow action.

So I think the fastest and correct operation is convert the String column to Float in your mongodb database. And then you can use normal .sort('-detail_info.overall_rating') to get things done.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download