Mongodb 条件排序

jon*_*nes 5 mongoose mongodb

我想在sort子句中添加一个字段,仅用于一天前创建的那些文档。假设在我的集合中,mycollection我的文档有一个字段publishDate和其他一些字段,以下是我的查询:

db.getCollection('mycollection').aggregate([                                                                                                                         
{
    "$match": {   
        "expireDate": {  
            "$gte": ISODate("2019-03-14T00:00:00.000Z")
        },
        "publishDate": {  
            "$lt": ISODate("2019-03-15T00:00:00.000Z")
        },
        "isPublished": true,     
        "isDrafted": false,  
        "deletedAt": {      
            "$eq": null   
        },
        "deleted": false,  
        "blocked": {     
            "$exists": false  
        }
    }
 },
 {
     "$sort": {    
         "isFeatured": -1,   // What I want is to add this field in sort clause by condition, when publishDate is yesterday, otherwise ignore it
         "refreshes.refreshAt": -1,  
         "publishDate": -1,   
         "_id": -1   
     }
 },
 {  
     "$skip": 0  
 },
 {   
     "$limit": 12  
 },
 {
     "$project": {
         "position": 1      
      }
 }])
Run Code Online (Sandbox Code Playgroud)

Mos*_*ius 6

创建一个虚拟字段,它代表应显示在列表顶部的条目的值,然后根据该字段对条目进行排序。您可以使用$addFields$cond运算符来完成它。

实现将是这样的:

// ...
{
  "$addFields": {
    "isFeaturedSort": {
      "$cond": {
        "if": {
          "$and": {
            "publishDate": {
              "$gte": ISODate("2019-03-14T00:00:00.000Z"),
            },
            "$eq": ["isFeatured", true],
          },
        },
        "then": 1,
        "else": 0,
      },
    },
  },
},
{
  "$sort": {
    "isFeaturedSort": -1, // changed
    "refreshes.refreshAt": -1,
    "publishDate": -1,
    "_id": -1,
  },
},
// ...
Run Code Online (Sandbox Code Playgroud)

请注意,$addField仅适用于 MongoDB 3.4 及更高版本。片段代码也可能包含错误。