Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb conditional sort

I want to add a field to the sort clause, for only those documents that created one day ago. Suppose in my collection mycollection my documents have a field publishDate, and some other fields, and following is my query:

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      
      }
 }])
like image 568
jones Avatar asked Mar 14 '19 09:03

jones


People also ask

Does MongoDB support sorting?

Sort and Index UseMongoDB can obtain the results of a sort operation from an index which includes the sort fields. MongoDB may use multiple indexes to support a sort operation if the sort uses the same indexes as the query predicate.

How do I sort data in MongoDB query?

To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

Which are the conditional operators in MongoDB?

A conditional operator compares two expressions and fetched documents from mongodb collection. In this page we are going to discuss about the conditional operators and usage of conditional operators. Our database name is 'myinfo' and our collection name is 'testtable'.

How do I sort a case insensitive in MongoDB?

This means the only way to sort case insensitive currently is to actually create a specific "lower cased" field, copying the value (lower cased of course) of the sort field in question and sorting on that instead.


1 Answers

Create a virtual field which represents a value for the entries that should be shown on top of the list, then sort entries based on that field. You can use $addFields and $cond operators to accomplish it.

The implementation would be something like this:

// ...
{
  "$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,
  },
},
// ...

Please notice that $addField only work in MongoDB 3.4 and further. also the snippets code may contain errors.

like image 115
Mosius Avatar answered Oct 03 '22 03:10

Mosius