以下是我的收藏架构。
我不知道如何应用分页并在聚合查询中获取总照片数。我知道这可能,但我尝试了很多,但我没有解决问题。指导我以下问题。
如果有任何优化的解决方案,那么请指导我。
照片:
{_id: 1, photo_name: '1.jpg', photo_description: 'description 1', album_id: 1},
{_id: 2, photo_name: '2.jpg', photo_description: 'description 2', album_id: 1},
{_id: 3, photo_name: '3.jpg', photo_description: 'description 3', album_id: 1},
{_id: 4, photo_name: '4.jpg', photo_description: 'description 4', album_id: 2},
{_id: 5, photo_name: '5.jpg', photo_description: 'description 5', album_id: 2},
{_id: 6, photo_name: '6.jpg', photo_description: 'description 6', album_id: 2}
专辑:
{_id: 1, album_name: "my album 1", album_description: "album description 1", emoji_id: 1},
{_id: 2, album_name: "my album 2", album_description: "album description 2", emoji_id: 2},
{_id: 3, album_name: "my album 3", album_description: "album description 3", emoji_id: 3},
{_id: 4, album_name: "my album 4", album_description: "album description 4", emoji_id: 4},
{_id: 5, album_name: "my album 5", album_description: "album description 5", emoji_id: 5}
表情符号:
{_id: 1, emoji_name: "1.jpg"},
{_id: 2, emoji_name: "2.jpg"},
{_id: 3, emoji_name: "3.jpg"},
{_id: 4, emoji_name: "4.jpg"},
{_id: 5, emoji_name: "5.jpg"},
{_id: 6, emoji_name: "6.jpg"},
{_id: 7, emoji_name: "7.jpg"},
{_id: 8, emoji_name: "8.jpg"}
测试记录分页:
2
预期产出:
[
{
album_id: 1,
album_name: "my album 1",
album_emoji: "1.jpg",
total_photos: 3,(total photo counts of all photos of paritcular album)
photos: [
{
{_id: 1, photo_name: '1.jpg', photo_description: 'description 1'},
{_id: 2, photo_name: '2.jpg', photo_description: 'description 2'}
}
]
}
]
目前的查询:
db
.album
.aggregate([
{
$lookup:{
from:"photo",
localField:"_id",
foreignField:"album_id",
as:"photo"
}
},
{
$lookup:{
from:"emoji",
localField:"album_emoji",
foreignField:"_id",
as:"emoji"
}
},
{
$project:{
album_name:"$album_name",
album_description:"$album_description",
album_emoji:"$emoji.image_name",
photo:"$photo"
}
},
{
$match:{
_id: 1
}
}
])
.toArray();
现在输出:
[{
"_id" : 1,
"album_name" : "my album 1",
"album_emoji" : [
"1.png"
],
"photo" : [
{_id: 1, photo_name: '1.jpg', photo_description: 'description 1', album_id: 1},
{_id: 2, photo_name: '2.jpg', photo_description: 'description 2', album_id: 1},
{_id: 3, photo_name: '3.jpg', photo_description: 'description 3', album_id: 1},
]
}]
答案 0 :(得分:2)
您可能需要检查$slice并稍微调整$project
阶段
...
$project:{
album_name:"$album_name",
album_description:"$album_description",
album_emoji:"$emoji.image_name",
photo: { $slice: [ "$photo", 0, 2 ] }
}
...
只需将不同的值传递给$slice
运算符即可获取不同的页面