发出查询并显示嵌入式文档的mongodb聚合结果

时间:2017-06-18 05:35:59

标签: mongodb aggregation-framework

我试图显示mongodb嵌入式文档的聚合结果。我想查询某些查询参数的嵌入文档,并显示只有子文档的分页结果。但我有一些问题显示数据。该集合的当前格式如下;

{ 
"_id" : ObjectId("5944b9d81b7bfc4d925d9e53"), 
"deleted" : false, 
"album_name" : "pokhara trip", 
"album_description" : "album description of my-album", 
"active" : "true", 
"url_slog" : "pokhara-trip", 
"images" : [
    {
        "_id" : ObjectId("5944bd111b7bfc4d925d9e55"), 
        "deleted" : true, 
        "image_title" : "test image 1", 
        "image_alt_text" : "test image alt text", 
        "image_description" : "test image detail", 
        "active" : "true"
    }, 
    {
        "_id" : ObjectId("5944bd591b7bfc4d925d9e56"), 
        "deleted" : true, 
        "image_title" : "test image 1", 
        "image_alt_text" : "test image alt text", 
        "image_description" : "test image detail", 
        "active" : "true"
    }
]

}

我使用聚合框架来查询上面的集合并只显示images子文档。我想只显示那些未标记为已删除的文档。

我已完成以下查询并显示结果。 但是我遇到了分页和查询子文档的问题。

下面是我的代码;

const queryOpts = {};
    const queryOptsImage = {};

    queryOpts._id = ObjectId(req.params.albumId);
    queryOpts.deleted = false;
    queryOptsImage["images"] = {
        'deleted': false
    };

    console.log(queryOpts);
    console.log('--------------------------------------');

    const galleryImages = await req.db.collection('ImageGalleryAlbum').aggregate(
        {
            $unwind:"$images"
        },
        {
            $match: queryOpts
        },
        {
            $project: projectionImageFields
        },
        {
            $group: {
                _id: null,
                images: { $push: "$images" }
            }
        },
        {
            $unwind:"$images.images"
        },
        // {
        //     $limit:pagerOpts.perPage
        // },
        // {
        //     $skip:pagerOpts.perPage * (pagerOpts.page-1)
        // },

    ).toArray();

    // const imagesArr =
    console.log(galleryImages);

我的结果低于结果:

    [
  {
    "images": [
      {
        "_id": "5944bd111b7bfc4d925d9e55",
        "image_title": "test image 1",
        "image_alt_text": "test image alt text",
        "image_description": "test image detail",
        "active": "true"
      },
      {
        "_id": "5944bd591b7bfc4d925d9e56",
        "image_title": "test image 1",
        "image_alt_text": "test image alt text",
        "image_description": "test image detail",
        "active": "true"
      }
    ]
    }
]

我想要的是我希望这些图像文档位于顶级数组。 没有{和图像数组。

0 个答案:

没有答案