簡體   English   中英

按 $cond mongoose 聚合 $sort

[英]Aggregate $sort by $cond mongoose

我有sortValue ,即"title-asc""title-desc""createdAt-asc""createdAt-desc" ,並將其拆分為sortVar ("title", " sortType ") 和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 ......我是貓鼬的新手..所以我無法按條件排序..如果有人能幫助我,我會很高興)

先用$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
             }  
          }
    );

}

如果沒有索引,那應該沒問題。 在這種情況下,限制也應該有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM