Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

253
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda