【问题标题】:How to resort the collection in MongoDB?如何在 MongoDB 中使用集合?
【发布时间】:2017-05-25 19:30:35
【问题描述】:

我们在 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 例如(订单)。所以最后一个总是在底部。

我们如何再次实现这一目标?

【问题讨论】:

  • 你集合中的_id字段是ObjectId类型还是数值?
  • _id 字段是 guid
  • 简单的解决方案是在检索文档后反转文档的顺序。请参阅下面的答案。

标签: javascript node.js mongodb mongodb-query aggregation-framework


【解决方案1】:

您需要使用聚合框架。

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

【讨论】:

  • 没有意识到这有 agregate 方法。谢谢
【解决方案2】:

最简单的做法是颠倒查询返回的记录顺序。因此,与其获取流,不如将响应转换为数组并使用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)

    })
});

【讨论】:

    猜你喜欢
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 2021-12-07
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多