Thomas Morris
Thomas Morris

Reputation: 822

node js how to sort a collection

I have a mongodb collection which has a large quantity of entries. + 10000.

All of these have the same paramters:

I am receiving this via a get request from my mobile app however the order is not correct.

How can I sort my collection by the Val string which is a number going from 1 to 10000 in this case.

I am using mongoose mongodb and node js.

Presently I query the collection and get 5 results send them and then loop another 5 until I have read all the results.

So I need to sort the collection out prior to sending this data.


app.get("/testmethod", function(req, res)
{

    mongoose.connect("mongodb://localhost:27017/CTI", {useNewUrlParser: true},function(err, client){
        if(err) {
            console.log(err)
        }
        else
        {
            client.db.collection("datas").find().limit(items_to_send).skip(Sent_data).toArray(function(err, result) {
            if (err) {throw err;}
            //console.log(result);
            Sent_data = Sent_data + items_to_send;
            db.close();

            var D1_T1 = result[0].T1_String;
            var D1_T2 = result[0].T2_String;
            var D2_T1 = result[1].T1_String;
            var D2_T2 = result[1].T2_String;
            var D3_T1 = result[2].T1_String;
            var D3_T2 = result[2].T2_String;
            var D4_T1 = result[3].T1_String;
            var D4_T2 = result[3].T2_String;
            var D5_T1 = result[4].T1_String;
            var D5_T2 = result[4].T2_String;
            
            res.status(200).send({
                D1_T1: D1_T1,
                D1_T2: D1_T2,
                D2_T1: D2_T1,
                D2_T2: D2_T2,
                D3_T1: D3_T1,
                D3_T2: D3_T2,
                D4_T1: D4_T1,
                D4_T2: D4_T2,
                D5_T1: D5_T1,
                D5_T2: D5_T2
                });
            });
        }//End of else
    });//End of connect
});

What I want is a sort to order the entire collection by the val string field which goes from 1-10000

Upvotes: 0

Views: 228

Answers (1)

Gibbs
Gibbs

Reputation: 22974

You have as below

client.db.collection("datas").find().limit(items_to_send).skip(Sent_data)

You can add .sort({fieldName:sortOrder})

sort order: 1 / -1(desc)

client.db.collection("datas").find().limit(items_to_send)
                  .skip(Sent_data).sort({"val_string":1})

Sort follows lexicographical order so no problem of being string.

Upvotes: 1

Related Questions