簡體   English   中英

如何在MongoDB中使用該集合?

[英]How to resort the collection in MongoDB?

我們在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); 
    });
});

如您所見,查詢是輸入的最后20條記錄的集合。 但是從這個結果我們想再次使用_id中的1,所以在列表中我們將使用ID 55 - 75(例如)。 所以最后一個總是在底部。

我們如何再次實現這一目標?

您需要使用聚合框架。

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); 
    });
});

最簡單的方法是顛倒查詢返回的記錄順序。 因此,在通過套接字發送之前,不是獲取流,而是將響應轉換為數組並使用reverse()函數來反轉其中的記錄順序!

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)

    })
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM