我對mongodb不是很有經驗,所以也許有人可以幫助我。我有一個這樣的集合:
{ user: 1, type: 0 , ... },
{ user: 1, type: 1, ... },
{ user: 1, type: 1, ... },
...
現在我想要按型別分組的特定用戶檔案,然后排序 偏移和限制。IE。喜歡:
[ { $match: { user: 1 } },
{ $facet: {
type0: [
{ $match: { type: 0 },
{ $sort: ... },
{ $skip: offset0 },
{ $limit: limit0 }
],
type1: [
{ $match: { type: 1 },
{ $sort: ... },
{ $skip: offset1 },
{ $limit: limit1 }
]
}
]
這可行,但是:有沒有辦法也可以獲得每種型別的總數?$facet 中的 $facet 是不允許的,但可能有一些完全不同的方式?還是最終必須對每種型別進行聚合呼叫?
uj5u.com熱心網友回復:
像這樣的東西:
db.collection.aggregate([
{
$match: {
user: 1
}
},
{
$facet: {
type0: [
{
$match: {
type: 0
}
},
{
$sort: {
type: -1
}
},
{
$skip: 1
},
{
$limit: 2
}
],
type1: [
{
$match: {
type: 1
}
},
{
$sort: {
type: -1
}
},
{
$skip: 1
},
{
$limit: 2
}
],
counts: [
{
$group: {
"_id": "$type",
cnt: {
$sum: 1
}
}
},
{
$project: {
type: "$_id",
cnt: 1,
_id: 0
}
}
]
}
}
])
解釋:您在 face 中再添加一個名為“counts”的階段,以對兩種不同型別的總計數進行分組。
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/422847.html
標籤:
