我有一個包含類別和時間戳的博客文章串列。現在,如果我想按時間順序對它們進行排序,但將每個類別的出現限制為,例如,每個類別只有 3 個帖子,那么常規 $group 似乎不是正確的方法。topN 也是如此,因為它將這些帖子按類別分組,但我丟失了按時間順序排列的串列。
uj5u.com熱心網友回復:
您仍然可以使用"$group"with"$topN"和然后,例如,在其后使用另一個"$group"、排序"$unwind"、和"$replaceWith"。
注意:這將給出最早的帖子。如果您想要最新的帖子,您可以調整排序順序。
db.blogPosts.aggregate([
{ // get max 3 items from category
// sorted by timestamp
"$group": {
"_id": "$category",
"postsTop3": {
"$topN": {
"n": 3,
"sortBy": {"timestamp": 1},
"output": "$$ROOT"
}
}
}
},
{ // aggregate all top3's
"$group": {
"_id": null,
"posts": {"$push": "$postsTop3"}
}
},
{ // sort them all by timestamp
"$set": {
"posts": {
"$sortArray": {
"input": {
"$reduce": {
"input": "$posts",
"initialValue": [],
"in": {
"$concatArrays": ["$$value", "$$this"]
}
}
},
"sortBy": {"timestamp": 1}
}
}
}
},
{"$unwind": "$posts"},
{"$replaceWith": "$posts"}
])
試試mongoplayground.net。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/524512.html
