MongoDB How to sort an array of objects without using aggregate & group?

juliascoding

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});
Charchit Kapoor

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

how to group and sort an array of objects

Mongodb aggregate by using input array

Mongodb aggregate sort and limit within group

MongoDB aggregate, how to addToSet each element of array in group pipeline

Nodejs Mongodb get first element of array using find without aggregate

MongoDB aggregate + $match + $group + Array

MongoDb Aggregate group and sort applications

How to sort date using aggregate from mongodb

how to sort array of objects in mongodb

How can I aggregate/group an Array of Objects by property value?

how to sort aggregate - Mongodb

How to sort Javascript objects in an array using regex

How to sort an array of objects using two properties but conditionally group in the sort order depending on a condition?

How to use aggregate to group mongodb

how group and sort array objects

How to get the count of element with non-empty-array-field when group in mongodb aggregate using Spring Data Mongo?

How to aggregate with group by and sort correctly

How to sort a $group aggregate output with mongodb

MongoDB aggregate objects with an array of objects?

How to use aggregate for group by in mongodb

How to use promql group by without using aggregate functions in Grafana

Aggregate & Sort by Inner Array in Spring Data MongoDB

MongoDB Query: How can I aggregate an array of objects as a string

MongoDB - Sort inner array with Aggregate

How to filter an array of objects to remove elements based on condition in MongoDB aggregate?

how can i sort data with a array element in mongodb without using unwind

MongoDB aggregate $group $sum that matches date inside array of objects

MongoDB aggregate group and count a nested array without Unwinding

Mongoose Filter & Sort Array of Objects Using Aggregate