К сожалению, вы пытаетесь сделать две основные вещи, которые Монго в настоящее время очень плохо делает:
- сортировка массива
- объединение массива в виде строки
Тем не менее, мы можем применить несколько этапов, таких как:
// { id: 1, roles: ["marketing", "admin", "user"], b: 42 }
// { id: 2, roles: ["admin"], b: 11 }
// { id: 3, roles: [], b: 1 }
db.collection.aggregate([
// First thing, let's handle empty arrays by replacing them with
// an array containing `""`. This way, the next stage (`$unwind`)
// will not get rid of these empty arrays. This might not be needed
// if you know you'll always have a role for a user. `roles: []`
// becomes `roles: [""]` other arrays are left untouched:
{ $addFields: {
roles: { $cond: {
if: { $eq: [ { $size: "$roles" }, 0 ] }, then: [""], else: "$roles"
}}
}},
// Transforms each document in as many documents as there are items in
// `roles`. For instance, `{ id: 1, roles: ["marketing", "admin", "user"], b: 42 }`
// becomes these 3 documents: `{ id: 1, roles: "marketing", b: 42 }`,
// `{ id: 1, roles: "admin", b: 42 }` and `{ id: 1, roles: "user", b: 42 }`
// That's also why we handled empty arrays in the previous stage:
{ $unwind: "$roles" },
// Now we can alphabetically sort all documents on the `roles` field:
{ $sort: { roles: 1 } },
// And we can transform back roles to arrays by grouping on `id` using
// `$push` within a `$group` stage. Since this preserves the order, the
// `roles` array is now sorted (due to the `$sort` stage applied
// just before on unwind elements). Note that you have to specify all
// other fields in your documents that you want to keep using `$first`.
// At this point you'll get `{ _id: 1, roles: ["admin", "marketing", "user"], b: 42 }`:
{ $group: { _id: "$id", roles: { $push: "$roles" }, b: { $first: "$b" } } },
// Finally, we can join an array of strings as a string by coupling
// `$reduce` and `$substr` operations:
{ $addFields: { roles: {
// The `$substr`ing handles results of `$reduce` such as
// `", admin, marketing"` by removing the first 2 characters:
$substr: [
// `$reduce` joins elements by applying `$concat` as many times as
// their are items in the array:
{ $reduce: {
input: "$roles",
initialValue: "",
in: { $concat: ["$$value", ", ", "$$this"] }
}},
2,
-1
]
}}},
// And, you can obviously sort the resulting documents on this field:
{ $sort: { roles: -1 } }
])
// { _id: 3, roles: "", b: 1 }
// { _id: 2, roles: "admin", b: 11 }
// { _id: 1, roles: "admin, marketing, user", b: 42 }
Обратите внимание, что я немного упростил вашу проблему, используя чистый массив ролей для ввода. Чтобы добраться до этой точки, вы можете сначала применить преобразование $map
, например:
// { roles: [{ id: 1, role: "admin" }, { id: 2, role: "marketing" }] }
db.collection.aggregate({ $addFields: { roles: { $map: { input: "$roles", as: "role", in: "$$role.role" } } } })
// { roles: [ "admin", "marketing" ] }