I want to return an array, which is a property inside my mongo model/document, and I want that array to be sorted.
My MongoDB document looks like:
JavaScript
x
18
18
1
_id: ObjectID("6248e49c88ff07aedee8c000")
2
title: "School"
3
items: [
4
{
5
sort: 2,
6
name: "homework"
7
},
8
{
9
sort: 1,
10
name: "exam"
11
},
12
{
13
sort: 3,
14
name: "essay"
15
},
16
17
]
18
And I’m trying to return:
JavaScript
1
16
16
1
items: [
2
{
3
sort: 1,
4
name: "exam"
5
},
6
{
7
sort: 2,
8
name: "homework"
9
},
10
{
11
sort: 3,
12
name: "essay"
13
}
14
15
]
16
I have tried aggregation:
JavaScript
1
14
14
1
app.get("/api/v1/lists/:id", async (req,res) =>{
2
3
List.aggregate([{
4
"$match" :{"_id": req.params.id}
5
},{
6
"$unwind" : "$items"
7
} , {
8
"$sort" : {"sort": 1}
9
}
10
], (err, items)=>{
11
res.json(items)
12
})
13
}
14
Advertisement
Answer
Mongo Playground reference Since $unwind returns the arrays as objects, we are using the $group to push the objects back into the items array
JavaScript
1
20
20
1
db.collection.aggregate([
2
{
3
$unwind: "$items"
4
},
5
{
6
$sort: {
7
"items.sort": 1
8
}
9
},
10
{
11
$group: {
12
_id: "$_id",
13
items: {
14
$push: "$items"
15
}
16
}
17
},
18
19
])
20
Output –
JavaScript
1
20
20
1
[
2
{
3
"_id": 1.212112e+06,
4
"items": [
5
{
6
"name": "exam",
7
"sort": 1
8
},
9
{
10
"name": "homework",
11
"sort": 2
12
},
13
{
14
"name": "essay",
15
"sort": 3
16
}
17
]
18
}
19
]
20