Reputation: 172
I have a collection that looks like this:
{
"_id" : "customer1",
"verarray" : [
"10.5.0-50_0",
"11.5.0-30_0"
]
}
{
"_id" : "customer2",
"verarray" : [
"11.0.0-30_0",
"11.5.0-80_0",
"12.5.0-111_0",
"13.3.0.21_0.31125",
"13.5.0-20_0"
]
}
{
"_id" : "customer3",
"verarray" : [
"11.5.0-95_0",
"12.6.0.131_0.33392",
"10.0.0-5_0",
"11.5.0.20_0.22028",
"12.6.0.131_0.33392"
]
}
As you can see, the 3rd customer array is not in order. I want to sort each verarray
. How do I do that?
Thank you
Upvotes: 1
Views: 33
Reputation: 17925
You can use $unwind
to unwind array, sort it & then re-create the same array by grouping on condition _id
.
db.collection.aggregate([
{ $unwind: "$verarray" },
{ $sort: { verarray: 1 } }, // Using 1 for asc & use -1 for desc order
{ $group: { _id: "$_id", verarray: { $push: "$verarray" } } }
])
Test : mongoplayground
Ref : aggregation
Upvotes: 1