search

Home  >  Q&A  >  body text

javascript - mongoose sorting of query results

The set of collections I now get through mongoose query looks like this:

[{
    _id: "123456",
    sex: 0
},{
    _id: "222222",
    sex: 1
},{
    _id: "111111",
    sex: 1
},{
    _id: "333333",
    sex: 0
}]

I hope it can be sorted like this:

[{
    _id: "123456",
    sex: 0
},{
    _id: "333333",
    sex: 0
},{
    _id: "111111",
    sex: 1
},{
    _id: "222222",
    sex: 1
}]

means that under the condition that sex is in ascending order, _id is in ascending order again. I currently set it when querying in mongoose:

options: {
    sort: {
        _id: 1
    }
}

This becomes an array in ascending order _id, and then a loop operation is performed on the front end to sort it. Is there any good way to directly arrange the data when querying the database?

滿天的星座滿天的星座2794 days ago811

reply all(1)I'll reply

  • 巴扎黑

    巴扎黑2017-05-02 09:28:10

    For reference:

    collection.find({}).sort({'sex': 1,'_id':1}).exec(callback)

    Love MongoDB! Have Fun!


    MongoDB Chinese Community Shenzhen User Conference

    This Saturday, let’s make an appointment

    Please enter for details

    reply
    0
  • Cancelreply