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

243
Views
¿Cómo recurrir la colección en MongoDB?

Tuvimos esta siguiente consulta en nuestro 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); }); });

Como puede ver, la consulta es una colección de los últimos 20 registros ingresados. Pero luego, a partir de este resultado, nos gustaría recurrir nuevamente a 1 en _id, por lo que en la lista tendremos ID 55 - 75, por ejemplo (el orden). Así que el último siempre en la parte inferior.

¿Cómo logramos esto de nuevo?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Necesita usar el marco de agregación.

 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

Lo más sencillo será invertir el orden de los registros devueltos por la consulta. Entonces, en lugar de obtener una transmisión, convierta la respuesta en una matriz y use la función reverse() , para invertir el orden de los registros en ella, ¡antes de enviarla a través del 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!