按$ cond猫鼬汇总$ sort

时间:2020-03-09 17:38:20

标签: node.js sorting mongoose aggregate

我有sortValue,分别是"title-asc""title-desc""createdAt-asc""createdAt-desc",并将其拆分为sortVar(“标题” ,“ 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 ...我是猫鼬的新手。.所以我无法满足条件。.如果有人可以帮助我,我将非常高兴)

1 个答案:

答案 0 :(得分: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
             }  
          }
    );

}

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