We had this following query in our Node.JS
mongo.connect('mongodb://XXX:[email protected]: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?
Using the sort() method will increase the readability of a query, which leads to a better understanding of a given dataset. Not only that, sorted data will be used by developers to write more complex algorithms. (This article is part of our MongoDB Guide.
If the sort keys correspond to the index keys or an index prefix, MongoDB can use the index to sort the query results. A prefix of a compound index is a subset that consists of one or more keys at the start of the index key pattern. The following query and sort operations use the index prefixes to sort the results.
The default internal sort order (or natural order) is an undefined implementation detail.
You can check the created collection by using the command show collections. The following example shows the syntax of createCollection () method with few important options − In MongoDB, you don't need to create collection. MongoDB creates collection automatically, when you insert some document.
renameCollection () obtains an exclusive lock on the source and target collections for the duration of the operation. All subsequent operations on the collections must wait until renameCollection () completes. Prior to MongoDB 4.2, renaming a collection within the same database with renameCollection required obtaining an exclusive database lock.
MongoDB stores data records as documents (specifically BSON documents) which are gathered together in collections. A database stores one or more collections of documents. In MongoDB, databases hold one or more collections of documents. To select a database to use, in mongosh, issue the use <db> statement, as in the following example:
The insertOne () operation creates both the database myNewDB and the collection myNewCollection1 if they do not already exist. Be sure that both the database and collection names follow MongoDB Naming Restrictions. MongoDB stores documents in collections. Collections are analogous to tables in relational databases.
You need to use the Aggregation Framework.
mongo.connect('mongodb://XXX:[email protected]: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);
});
});
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:[email protected]: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)
})
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With