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:
- unwinds the array
- sorts by
friends.name
- 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 $unwind
ing the updates
array, sorting the resulting docs by date
, and then $group
ing 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
How to Fire and Forget a Promise in Nodejs (Es7)
How to Access Svg Elements with JavaScript
What Values Can a Constructor Return to Avoid Returning This
How to Get a JavaScript Object's Class
How to Set the Value Property in Angularjs' Ng-Options
How to Replace Innerhtml of a Div Using Jquery
Required Field Validations Not Working in Jquery Popup MVC 4
Es6 Destructuring Function Parameter - Naming Root Object
What Is the Reason JavaScript Settimeout Is So Inaccurate
Why Is My React Component Is Rendering Twice
What's Wrong with Awaiting a Promise Chain
How to Sort 2 Dimensional Array by Column Value
Why Does the Month Argument Range from 0 to 11 in JavaScript's Date Constructor
Working with Select Using Angularjs's Ng-Options
How to Get File Extensions with JavaScript
Parseint VS Unary Plus, When to Use Which