How to Sort Array Inside Collection Record in Mongodb

How to sort array inside collection record in MongoDB?

You will need to manipulate the embedded array in your application code or using the new Aggregation Framework in MongoDB 2.2.

Example aggregation in the mongo shell:

db.students.aggregate(
// Initial document match (uses index, if a suitable one is available)
{ $match: {
_id : 1
}},

// Expand the scores array into a stream of documents
{ $unwind: '$scores' },

// Filter to 'homework' scores
{ $match: {
'scores.type': 'homework'
}},

// Sort in descending order
{ $sort: {
'scores.score': -1
}}
)

Sample output:

{
"result" : [
{
"_id" : 1,
"name" : "Aurelia Menendez",
"scores" : {
"type" : "homework",
"score" : 71.76133439165544
}
},
{
"_id" : 1,
"name" : "Aurelia Menendez",
"scores" : {
"type" : "homework",
"score" : 34.85718117893772
}
}
],
"ok" : 1
}

mongodb sorting children of an array in a document

An option is to run an aggregation that:

  1. unwinds the array
  2. sorts by friends.name
  3. regroups

The pipeline should look something like this:

db.collection.aggregate([
{ $match: { name: 'dan' }},
{ $unwind: '$friends' },
{ $sort: { 'friends.height': -1 }},
{ $group: { _id: '$name', friends: { $push: '$friends'}}])

how to sort array inside collection in mongoDB using node js

Use this one:

db.collection.aggregate([
{ $unwind: "$QUERIES" },
{ $sort: { "QUERIES.createdAt": -1 } },
{
$group: {
_id: { _id: "$_id", TICKET_ID: "$TICKET_ID" },
QUERIES: { $push: "$QUERIES" }
}
},
{ $replaceRoot: { newRoot: { $mergeObjects: ["$$ROOT", "$_id"] } } }
])

Mongo playground

Sort the array in the document with MongoDB

I see the problem. People are searching for and finding this stackoverflow answer:

how to sort array inside collection record in mongoDB

It's wrong, since it never "reconstructs" the array.

You do that with $group and $push, and since you are grouping you will want $first for the other fields in the document you want:

db.TrafficStatistic.aggregate([
{ "$unwind": "$statistic" },
{ "$sort": { "_id": 1, "statistic.data.desktop.users": 1 } },
{ "$group": {
"_id": "$_id",
"monthStart" : { "$first": "$monthStart" },
"monthEnd" : { "$first": "$monthEnd" },
"date" : { "$first": "$date" },
"statistic": { "$push": "$statistic" }
}}
])

Note also the $sort is applied to both the "_id" and the other field to sort. This is so the sorting is applied per document and is important when the document details are put back together in $group.

Now the document looks the same as it did, but this time the array members are sorted.

Mongodb sort inner array

You can do this by $unwinding the updates array, sorting the resulting docs by date, and then $grouping them back together on _id using the sorted order.

db.servers.aggregate(
{$unwind: '$service.apps.updates'},
{$sort: {'service.apps.updates.date': 1}},
{$group: {_id: '$_id', 'updates': {$push: '$service.apps.updates'}}},
{$project: {'service.apps.updates': '$updates'}})

MongoDB sort by value in embedded document array

You need to use aggregation to sort n array

  • $unwind to deconstruct the array
  • $match to match the value
  • $sort for sorting
  • $group to reconstruct the array

Here is the code

db.collection.aggregate([
{ "$unwind": "$challengeDetails" },
{ "$match": { "challengeDetails.ID": 2 } },
{ "$sort": { "challengeDetails.pb": 1 } },
{
"$group": {
"_id": "$_id",
"username": { "$first": "$username" },
"challengeDetails": { $push: "$challengeDetails" }
}
}
])

Working Mongo playground

How to sort inner array elements while maintaining different sorting for outer documents?

You can use the below aggregation query.

$unwind the slots array followed by sorting the docs date asc and $group back on _id to get the sorted array.

$sort on name desc to sort the documents.

db.col.aggregate([
{"$unwind":"$slots"},
{"$sort":{"slots.date":1}},
{"$group":{"_id":"$_id","name":{"$first":"$name"},"slots":{"$push":"$slots"}}},
{"$sort":{"name":-1}},
])

mongodb unwind and sort array nested inside an array of documents

Demo - https://mongoplayground.net/p/Vt3GQx0tdXC

  • Add a new filed with to lower case using $toLower
  • Sot on the lower case value

   db.products.aggregate([
{ "$unwind": "$receipe" },
{ "$unwind": "$receipe.burger" },
{ $addFields: { "insensitiveName": { $toLower: "$receipe.burger.name" } } },
{ $sort: { "insensitiveName": 1 } }
])


Related Topics



Leave a reply



Submit