Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

250
Views
How to resort the collection in MongoDB?

We had this following query in our Node.JS

mongo.connect('mongodb://XXX:XXX@ds054XXX.mlab.com:54289/XXXdb', function (err, db) {
    var collection = db.collection('chatmessages')
    var stream = collection.find().sort({ _id: -1 }).limit(20).stream();
    stream.on('data', function (chat) { 
        socket.emit('user message', chat.content, chat.dateCreated); 
    });
});

As you can see, the query is a collection of last 20 records entered. But then from this result we would like to do resort again to 1 in _id so in the list we will have ID 55 - 75 for instance (the order). So the last one always at the bottom.

How do we achieve this again?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You need to use the Aggregation Framework.

mongo.connect('mongodb://XXX:XXX@ds054XXX.mlab.com:54289/XXXdb', function (err, db) {
    var collection = db.collection('chatmessages')
    var stream = collection.aggregate([
        { "$sort": { "_id": -1}}, 
        { "$limit": 20 }, 
        { "$sort": { "_id": 1 }}
    ]);
    stream.on('data', function (chat) { 
        socket.emit('user message', chat.content, chat.dateCreated); 
    });
});
over 4 years ago · Santiago Trujillo Report

0

The simplest thing to do will be to reverse the order of records returned by the query. So, instead of getting a stream, convert the response to array and use reverse() function, to reverse the order of records in it, before sending it through the socket!

mongo.connect('mongodb://XXX:XXX@ds054XXX.mlab.com:54289/XXXdb', function (err, db) {

    var collection = db.collection('chatmessages')

    collection.find().sort({ _id: _1 }).limit(20).toArray(function(err, docs) {

        if (err) {
            // handle error
        }

        docs.reverse();  // <-- This will reverse the order of records returned!


        // Send the the array of records through socket.
        socket.emit('user message', docs)

    })
});
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!