简化MongoDB聚合

Simplify MongoDB aggregation(简化MongoDB聚合)
本文介绍了简化MongoDB聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这种聚合按深度嵌套字段ObjectID对所有产品进行排序。

首先我填充CatalogProduct字段。

然后填充CatalogProduct内的类别。

按类别ID对所有数据排序(如果ID arr包含类别._id,则返回product)

按相反顺序排序,返回分页并按8限制分页。

然后获取没有分页和限制的所有已排序产品的总计数。

const sortedProducts = await StorageModel.aggregate([
                // Unite products arr and totalCount of sorted products
                {$facet: {
                    "sortedProducts": [
                        // populate catalogProduct ref by Id
                        { $lookup: {
                                from: "catalogs",
                                localField: "catalogProduct",
                                foreignField: "_id",
                                as: "catalogProduct"
                            } },
                        // deconstruct this Arr, because we get only one Object
                        { $unwind: "$catalogProduct" },
                        // populate category ref by Id inside catalogProduct object
                        { $lookup: {
                                from: "categories",
                                localField: "catalogProduct.category",
                                foreignField: "_id",
                                as: "catalogProduct.category"
                            } },
                        // deconstruct this Arr, because we get only one Object
                        { $unwind: "$catalogProduct.category" },
                        // returns product, if ids arr includes a catalogProduct.category._id
                        { $match: {
                                "catalogProduct.category._id": { $in: ids }
                            } },
                        // sort in reverse order
                        { $sort: { _id: -1 } },
                        // returns only *page
                        { $skip: (page - 1) * 8 },
                        /// limit result by 8
                        { $limit: 8 },
                    ],
                    // total count for pagination, the same operations
                    "totalCount": [
                        { $lookup: {
                                from: "catalogs",
                                localField: "catalogProduct",
                                foreignField: "_id",
                                as: "catalogProduct"
                            } },
                        { $unwind: "$catalogProduct" },
                        { $lookup: {
                                from: "categories",
                                localField: "catalogProduct.category",
                                foreignField: "_id",
                                as: "catalogProduct.category"
                            } },
                        { $unwind: "$catalogProduct.category" },
                        { $match: {
                                "catalogProduct.category._id": { $in: ids }
                            } },
                        // get total count of sorted data, without limit and pagination
                        {$count : "totalCount"},
                    ]
                    }},
            ]);
            
            products = sortedProducts[0].sortedProducts
            totalProducts = sortedProducts[0].totalCount.totalCount

我正在获取这样的数据:

[
  { sortedProducts: [ [Object], [Object] ], totalCount: [ [Object] ] }
]

而且很好。但我认为,聚合可以简化,我不需要重复操作来获得总计数,但我不知道如何进行。

推荐答案

可以观察起始阶段,直到2中重复$matchbycatalogProduct.category._id。因此,您可以简单地将它们提取出来,然后将后续阶段分别放入$facet

下面是我建议的代码版本:

StorageModel.aggregate([
    { $lookup: {
        from: "catalogs",
        localField: "catalogProduct",
        foreignField: "_id",
        as: "catalogProduct"
    } },
    // deconstruct this Arr, because we get only one Object
    { $unwind: "$catalogProduct" },
    // populate category ref by Id inside catalogProduct object
    { $lookup: {
            from: "categories",
            localField: "catalogProduct.category",
            foreignField: "_id",
            as: "catalogProduct.category"
        } },
    // deconstruct this Arr, because we get only one Object
    { $unwind: "$catalogProduct.category" },
    // returns product, if ids arr includes a catalogProduct.category._id
    { $match: {
        "catalogProduct.category._id": { $in: ids }
    } },
    // Unite products arr and totalCount of sorted products
    {$facet: {
        "sortedProducts": [
            // populate catalogProduct ref by Id
            
            // sort in reverse order
            { $sort: { _id: -1 } },
            // returns only *page
            { $skip: (page - 1) * 8 },
            /// limit result by 8
            { $limit: 8 },
        ],
        // total count for pagination, the same operations
        "totalCount": [
            // get total count of sorted data, without limit and pagination
            {$count : "totalCount"},
        ]
        }},
]);

这篇关于简化MongoDB聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)