0

I want to sort an array of objects inside my modal and the only way to do it (as I saw) is the following:

...
const notifications = await Notification
            .aggregate([
                {$match: {to: userId}},
                {$unwind: '$messages'},
                {$sort: {'messages.createdAt':-1}},
                {$group: {
                        _id: '$_id',
                        createdAt: {$first: '$createdAt'},
                        messages: {$push: '$messages'},
                    }}
            ])
...

However, I am wondering if there is another way to do it. It seems that I have to do so many operations, even though all I want is to sort an array (grouping for example would make sense if I would actually change anything about the data but I dont). The only other way to do it I found was this:

const notifications = await Notification.findOne({to: userId}).sort({'messages.createdAt': -1})

but that doesnt sort my array in descending order, basically does nothing.

const notificationSchema = new mongoose.Schema({
    to: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    messages: [{
        title: {
            type: String,
            required: true
        },
        body: {
            type: String
        },
        isRead: {
            type: Boolean,
            default: false
        },
        createdAt: {
            type: Date,
            default: new Date()
        }
    }, ]
},{timestamps: true});

1 Answer 1

2

You can use $sortArray operator if you have MongoDB 5.2 or above. Otherwise, you can go through the path of unwinding and grouping. Or you can modify your update operation for the Notification model so that it already sorts, the messages by their createdAt, in descending order and you don't have to perform the sorting while fetching the notification using find method. Something like this:

db.collection.update({
  "notification": "Hello"
},
{
  "$push": {
    messages: {
      "$each": [
        {
          id: "4"
        }
      ],
      "$sort": {
        id: -1
      }
    }
  }
})

Playground link.

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you so much. How can I use it in my case - please see my link to same playground: mongoplayground.net/p/xujp_G7_rLV
Playground doesn't support all the update methods. I have updated your playground to make it work. Check this mongoplayground.net/p/UfOaJTZL-tO. @juliascoding
thanks, but how can I use each sort and still push my message (object) into the messages array? mongoplayground.net/p/_tbJP4Vh6XP
You should provide the message in $each array like this mongoplayground.net/p/ImXj_1XQCWH
Not as such, in fact it's efficient since sorting while saving, prevents sorting again and again, while fetching.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.