0

I have written mongo query with node.js. I have array object in my document. I want to apply pagination & sort on that array.

"user_notifications" : [
    {
        "_id" : ObjectId("59a7c30ecd6109c914c5fb5f"),             
        "notification_on" : ISODate("2017-09-28T10:00:44.828+0000"),      
        "procedure_id" : "59ccc84c1312ac3756944736"
    }, 
    {       
        "_id" : ObjectId("59db55ed57983b04534f0285"),            
        "notification_on" : ISODate("2017-10-09T10:56:45.235+0000"),             
        "procedure_id" : "59db55ed57983b04534f024d"            
    }, 
    {  
       "_id" : ObjectId("59db672b9700ef5f54f25b3a"),
       "procedure_id" : "59db672b9700ef5f54f25b0a",            
       "notification_on" : ISODate("2017-10-09T12:10:19.900+0000") 

    }, 
    {
        "_id" : ObjectId("59db694f89cb7e9954af26ad"),             
        "notification_on" : ISODate("2017-10-09T12:19:27.954+0000"),            
        "procedure_id" : "59db694f89cb7e9954af267d" 

    }
]

I want to sort “user_notification” array using “notification_on” key. I have used following code for pagination which is perfectly working fine.

UserModel.findOne({"_id":user._id},{user_notifications:{$slice:[skip, 
    limit]}}, function(err , user_obj){
    . 
    .
    .
});

But I am unable to sort records.

This question is different than other because I am retrieving only one record which has "user_notifications" object. I wanted to apply pagination for objects in this array & this array needs to sort by notification_on key.

Thanks

  • The `$slice` projection does not "sort" an array. The only way to sort an array in a document "at runtime" is to use aggregation and `$unwind` and `$sort` the array elements. There is then a `$slice` for the aggregation framework which "could" be applied to the elements. You would do better if you could to actually "update" the array with the sorted order as stored in the documents instead. All references listed. – Neil Lunn Nov 16 '17 at 05:41
  • `db.user_notifications.find().sort({"notification_on":1}) 1 for asc and -1 for desc` – Vignesh hawkeye Nov 16 '17 at 05:55
  • Thanks for reply. Can you provide me example for aggregation with $slice. I am using $slice to get chunk of objects. – Subodh Deshpande Nov 16 '17 at 10:54

0 Answers0