0

I'm having issue with sorting child element having multiple array of object.

e.g.

Collection: conversations

[
{
  "key" : "value",
  "receivers" : [
    { "userId" : 1, "updatedAt" : new Date() },
    { "userId" : 2, "updatedAt" : new Date() }

  ]
},
{
  "key" : "value",
  "receivers" : [
    { "userId" : 1, "updatedAt" : new Date() },
    { "userId" : 2, "updatedAt" : new Date() }

  ]
}
]

Now i'm finding result based on receivers.userId

conversation.find( { 'receivers.userId' : 1 } ).sort({ 'receivers.updatedAt' : -1 })

Here issue i'm facing is with sorting.. i need to sort record only on userId = 1 from child array. currently if userId: 2 has latest updated date then it is coming first.. as i need to consider updatedDate of userId:1

  • Does this answer your question? [How to sort array inside collection record in MongoDB?](https://stackoverflow.com/questions/13449874/how-to-sort-array-inside-collection-record-in-mongodb) – turivishal Jul 26 '21 at 05:31
  • it is not possible by find methods, you can use aggregate method, see above duplicate question. – turivishal Jul 26 '21 at 05:32
  • @turivishal thanks for reference. using aggregate it is working. i'm posting my own answer. – Pravin M. Dabhi Jul 26 '21 at 06:02

1 Answers1

0

By using aggregate we can achieve this.

db.getCollection('conversations').aggregate([
    {
      $addFields: {
        lastSent: {
          $let: {
            vars: {
              filtered: {
                $filter: {
                  input: "$receivers",
                  cond: { $eq: ["$$this.userId", 1177947885] }
                }
              }
            },
            in: { $max: "$$filtered.updatedAt" }
          }
        }
      }
    },
    { $sort: { lastSent: -1 } },
    { $project: { lastSent: 0 } }
  ])