Home > other >  How to sort nested array in MongoDB?
How to sort nested array in MongoDB?

Time:05-22

Mongo playground link: https://mongoplayground.net/p/BGtxQEBAvZh

I have an array field "opcoes", which I want to sort by date dt. Currently it is unsorted, e.g.

{
    "_id" : "w900c9b5a-666f-4857-92da-0b9c273dca40",
    "opcoes" : [
        {
            "dt" : ISODate("2021-11-16T11:17:55.386-03:00"),
            "text" : "2"
        },
        {
            "dt" : ISODate("2021-11-16T11:17:29.709-03:00"),
            "text" : "3"
        }
    ]
}

The expected result is:

{
    "_id" : "w900c9b5a-666f-4857-92da-0b9c273dca40",
    "opcoes" : [
        {
            "dt" : ISODate("2021-11-16T11:17:29.709-03:00") ,
            "text" : "3"
        },
        {
            "dt" : , ISODate("2021-11-16T11:17:55.386-03:00")
            "text" : "2"
        }
    ]
}

Can you help me? I was trying to use $SortArray but it doesn't recognize it. I get " Invalid $project :: caused by :: Unknown expression $sortArray ".

I created the array using $push:

{ 
    $group: { 
        _id: "$chat_key", 
        opcoes: { 
            $push: { 
                text: "$text", 
                dt: "$dt" 
            } 
        } 
    } 
}

Is there an option to sort inside a $push?

Thank you

CodePudding user response:

$sortArray is for mongoDB version 5.2 and higher, if you get this error, you are probably using an older version.

The best approach regardless of your version) is to to $sort before the $push:

db.collection.aggregate([
  {
    $sort: {dt: 1}
  },
  {
    $group: { 
    _id: "$chat_key", 
    opcoes: {$push: {text: "$text", dt: "$dt"}} 
  }
])

If you already have an array (and you can't control the pushing operation), and your version is older than 5.2, you can $unwind:

db.collection.aggregate([
  {
    $unwind: "$opcoes"
  },
  {
    $sort: {dt: 1}
  },
  {
    $group: {
      _id: "$_id",
      opcoes: {
        $push: {dt: "$opcoes.dt", text: "$opcoes.text"}
      }
    }
  }
])

playground

  • Related