I'm not very experienced with mongodb, so maybe someone can help me. I have a collection kind of like this:
{ user: 1, type: 0 , ... },
{ user: 1, type: 1, ... },
{ user: 1, type: 1, ... },
...
Now I want for a specific user documents grouped by type, then sorted offset & limit. ie. like:
[ { $match: { user: 1 } },
{ $facet: {
type0: [
{ $match: { type: 0 },
{ $sort: ... },
{ $skip: offset0 },
{ $limit: limit0 }
],
type1: [
{ $match: { type: 1 },
{ $sort: ... },
{ $skip: offset1 },
{ $limit: limit1 }
]
}
]
This works, but: Is there a way to also get the total count of every type? $facet within $facet is not allowed, but maybe some completly different way? Or will a have to make an aggregate call for every single type in the end?
CodePudding user response:
Something like this:
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
}
}
]
}
}
])
Explained: You add one more stage named "counts" in the faced to group the total count of the two different types.
