简体   繁体   中英

how to sort a mongodb database?

I got a collection that looks like,

[
  {"_id":"543a631d525dc7684bb730e3","word":"sda","description":"dsa"},
  {"_id":"543a634e525dc7684bb730e4","word":"dsa","description":"dasda"},
  {"_id":"543a6886525dc7684bb730e5","word":"sadas","description":"asaaa"}
]

I have trouble sorting the list by alphabetical order, what I've tried now is-

router.get('/userlist', function(req, res) {
    var db = req.db;
    db.collection('userlist').find().sort({ word: 1 })
    db.collection('userlist').find().toArray(function (err, items) {
        res.json(items);
    });
});

Does anyone have any idea how I can sort this list by word?

This is not how it will work, if you have any background from programming then you should know that the first db...find() will return the data (cursor) you want, but you are not storing that data in any variable, and in your second db....find() you are not applying the sort .

So, i know you have found the answer yourself, but still you can also use something like this,

router.get('/userlist', function(req, res) {
    db.collection('userlist').find().sort({ word: 1 }).toArray(function (err, items) {
        res.json(items);
    });
});

If you are using mongoose, you can sort as follows:

router.route('/userlist')

// CREATE ROUTE FOR USERLIST
// =========================
.get(function(req, res) {

  // SEND THE USERLIST AFTER SORTING THEM OUT IN ALPHABETICAL ORDER
  Snippets.find().sort({time: -1}).exec(function(err, items) {
    res.json(items);
  })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM