聚合框架- mongodb如何在聚合查询中应用分页和总照片计数



以下是我的收藏架构。

我不知道如何在聚合查询中应用分页并获得总照片计数。我知道这是可能的,但我试了很多,仍然没有解决问题。指导我解决以下问题。

如果有任何优化的解决方案,请指导我。

照片:

{_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}

Emoji:

{_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},
   ]
}]

您可能需要检查$slice并像这样调整您的$project阶段

 ...
 $project:{
    album_name:"$album_name",
    album_description:"$album_description",
    album_emoji:"$emoji.image_name",
    photo: { $slice: [ "$photo", 0, 2 ] }
 }
 ...

只需传递不同的值给$slice操作符来获得不同的页面

相关内容

  • 没有找到相关文章

最新更新