Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resort the collection in MongoDB?

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?

like image 869
dcpartners Avatar asked Jan 11 '17 05:01

dcpartners


People also ask

What is the use of sort () in MongoDB?

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.

What is sort key in MongoDB?

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.

What is the default sort order in MongoDB?

The default internal sort order (or natural order) is an undefined implementation detail.

How to check the created collection in MongoDB?

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.

How does renamecollection work in MongoDB?

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.

What is the difference between MongoDB and a database?

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:

What is Insertone() operation in MongoDB?

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.


2 Answers

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); 
    });
});
like image 160
styvane Avatar answered Oct 17 '22 01:10

styvane


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)

    })
});
like image 38
Santanu Biswas Avatar answered Oct 17 '22 01:10

Santanu Biswas