【问题标题】:How to get the last N elements with a matching key from a MongoDB collection如何从 MongoDB 集合中获取具有匹配键的最后 N 个元素
【发布时间】:2017-06-14 08:46:15
【问题描述】:

我有一个如下所示的文档集合:

[
 {
   "_id": "588cf61e5120ac11d4366f5c",
   "title": "This is a test entry",
   "entrybody": "This is the body of an entry",
   "creationdate": 1111,
   "author": "1223cllclclclc",
   "__v": 0
  },
 {
   "_id": "588cf6a556414f02f4e6a865",
   "title": "This is a new entry",
   "entrybody": "This is the body of an nuew entry",
   "creationdate": 11114040050505,
   "author": "1223cllclclclclslslsl",
   "__v": 0
 },
 {
   "_id": "588cf767fc2ede200cd5738e",
   "title": "This is a new entry",
   "entrybody": "This is the body of an nuew entry",
   "creationdate": 11114040050505,
   "author": "1223cllclclclclslslsl",
   "__v": 0
   }
  .....
]

我想获取每个作者的最后 n 条记录,然后按创建日期对它们进行排序,我已经查找了如何通过聚合来做到这一点,但我卡住了。

我需要集合的最后 N 个与特定键匹配的文档,例如作者,然后我必须按“创建日期”对该结果进行排序。我认为这与这个问题不同mongodb: how to get the last N records?

提前致谢。

【问题讨论】:

  • 这没有回答我的问题,它显示了如何获取集合的最后 N 个文档,但与获取与特定键匹配的最后 N 个记录然后按创建日期对结果进行排序没有任何关系。
  • 您只需要包含查询条件。试试db.collection.find({"author":"somevalue"}).sort({"creationda‌​te":-1}).limit(10);
  • 这将只返回一个作者的文档,我需要查询返回所有作者的最后 N 个文档。
  • 对不起,我看错了。您需要为此进行聚合。
  • 是的,但我坚持如何实现聚合以获得我需要的东西。

标签: mongodb mongoose


【解决方案1】:

你可以试试这样的。

$sort 处理最后一个creationdate 上每个author 的记录。

$group$project 为每个 author 挑选最后 N 条记录。

$unwind$sort 处理由creationdate 处理的记录。

db.collection.aggregate({
    $sort: {
        author: 1,
        creationdate: -1
    }
}, {
    $group: {
        _id: "$author",
        data: {
            $push: "$$ROOT"
        }
    }
}, {
    $project: {
        _id: 0,
        lastN: {
            $slice: ["$data", N]
        }
    }
}, {
    $unwind: "$lastN"
}, {
    $sort: {
        "lastN.creationdate": -1
    }
})

【讨论】:

  • 谢谢,这对我来说几乎成功了,我只需要使用 .sort() 按创建日期再次对生成的对象数组进行排序,以使其按需要工作。
  • Np。你不必排序。修复了答案,因为它缺少参考。最后一种是需要的。
【解决方案2】:

这里有一个通过forEach 方法解决问题的替代方法:

var result = {};
db.collection.find().sort({"author": 1, "creationda‌‌te":-1}).forEach(function(doc) { 
    if (!(doc.author in result)) { 
        result[doc.author] = [];
    }
    if (result[doc.author].length < 5) { 
        result[doc.author].push(doc); 
    } 
})

执行后,result 变量会填充以作者姓名分隔的文档

{
    'author1': [
        {doc1},
        {doc2}
    ],
    'author2': [
        {doc1},
        {doc2}
    ]
}

【讨论】:

    猜你喜欢
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-19
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多