簡體   English   中英

如何從 MongoDB 集合中獲取具有匹配鍵的最后 N 個元素

[英]How to get the last N elements with a matching key from a MongoDB collection

我有一個看起來像這樣的文檔集合:

[
 {
   "_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這個問題不同:如何獲取最后N條記錄?

提前致謝。

你可以嘗試這樣的事情。

$sort處理每個author在最后一次creationdate的記錄。

$group$project為每個author選擇最后 N 條記錄。

$unwind$sortcreationdate處理記錄。

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

這是在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}
    ]
}

暫無
暫無

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

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