How to resort to a collection in MongoDB?

We had the following request in 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 the last 20 entries entered. But then from this result we would like to resort again to 1 in _id, so in the list we will have ID 55 - 75, for example (order). So the last one is always down.

How can we achieve this again?

+6
source share
2 answers

You need to use an aggregation structure.

 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); }); }); 
+5
source

The easiest way to do this is to reorder the records returned by the request. Thus, instead of receiving the stream, convert the response into an array and use the reverse() function to reverse() order of the entries 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) }) }); 
+2
source

Source: https://habr.com/ru/post/1013972/


All Articles