【问题标题】:Aggregate $sort by $cond mongoose通过 $cond mongoose 聚合 $sort
【发布时间】:2020-06-21 15:35:53
【问题描述】:

我有sortValue,也就是"title-asc""title-desc""createdAt-asc""createdAt-desc",并拆分成sortVar(“title”,“createdAt”)和sortType(“asc ", "desc")
我想按 sortVar 和 sortType 条件对数据进行排序
所以我写了这样的聚合 ->

Product.aggregate([
      ...
      {
        $sort: {
          $cond: {
            if: {
              $eq: [sortVar, "title"]
            },
            then: {
              $cond: {
                if: {
                  $eq: [sortType, "asc"]
                },
                then: {
                  createdAt: 1
                },
                else: {
                  createdAt: -1
                }
              }
            },
            else: {

            }
          }
        }
      },
      {
        $sort: {
          $cond: {
            if: {
              $eq: [sortVar, "createdAt"]
            },
            then: {
              $cond: {
                if: {
                  $eq: [sortType, "asc"]
                },
                then: {
                  createdAt: 1
                },
                else: {
                  createdAt: -1
                }
              }
            },
            else: {

            }
          }
        }
      }
    ])

并返回错误$meta is the only expression supported by $sort right now...我是猫鼬的新手..所以我无法按条件排序..如果有人可以帮助我,我会很高兴)

【问题讨论】:

    标签: node.js sorting mongoose aggregate


    【解决方案1】:

    先用$cond添加一个新字段,方向可以作为变量传入:

      let direction= sortType === 'asc'?1: -1;   
    

    聚合:

    Product.aggregate(
    {
         $addFields:
               {
                 finalSortingValue:
                   {
                     $cond: [ {$eq: [sortVar, "title"], $title, $createdAt}, 
                   }
               }
    
          },
          {
           $sort:{
                finalSortingValue: direction
             }  
          }
    );
    

    编辑: 如果您已经在 title 和 createdAt 字段上有索引,它将对性能产生很大影响。 如果是这样的话,我觉得这样应该会更好

     let direction= sortType === 'asc'?1: -1;   
     if(sortVar === 'title'){   
        Product.aggregate(
              {
               $sort:{
                    title: direction
                 }  
              }
        );
    }else{
         Product.aggregate(
              {
               $sort:{
                    createdAt: direction
                 }  
              }
        );
    
    }
    

    如果没有索引,那应该没问题。在这种情况下,限制也应该有所帮助。

    【讨论】:

    • 我有一个问题......如果我在集合中有数十万个文档,它会杀死很多性能吗?如果是这样,我该怎么办?在排序之前我必须给出一个限制吗?或者它有更优雅的解决方案?
    猜你喜欢
    • 2017-10-12
    • 2017-05-23
    • 2021-12-16
    • 2013-06-16
    • 2023-03-17
    • 2016-02-28
    • 2016-05-30
    • 2019-02-25
    • 1970-01-01
    相关资源
    最近更新 更多