I have a structure like this:
[
{
"_id": "abc",
"field1": [], // array of subdocuments, may be empty
"field2": "somVal",
"field3": [ // array of subdocuments, may be empty
{
"fieldToSort": "bcdef"
},
{
"fieldToSort": "abcde"
}
]
},
{
"_id": "def",
"field1": [ // array of subdocuments, may be empty
{
"fieldToSort": "bcdef"
},
{
"fieldToSort": "abcde"
}
],
"field3": [] // array of subdocuments, may be empty
// field2 is missing
}
]
My documents have many fields in common, but may not all have the same fields.
The arrays to be sorted may be empty.
I just want to sort the values inside field1 and field3 alphabetically by some field, without affecting the sort order of all of the main documents.
I know that usually one uses unwind on arrays, then sorts, then groups. However, during grouping, I dont want to restore the original document field by field.
Is there another way?
Whatever the solution, the structure of the main documents cannot be altered.
The expected result here would be:
[
{
"_id": "abc",
"field1": [],
"field2": "somVal",
"field3": [
{
"fieldToSort": "abcde"
},
{
"fieldToSort": "bcdef"
}
]
},
{
"_id": "def",
"field1": [
{
"fieldToSort": "abcde"
},
{
"fieldToSort": "bcdef"
}
],
"field3": []
}
]