I have an aggregation pipeline that returns 20 tuples with known _id's:
[ { _id: 'AA', value: 5 },
{ _id: 'CD', value: 2 },
How to create a pipeline stage to order them in an arbitrary order?
For example 'CD', 'AA', 'EF', 'BC'.
CodePudding user response:
Query1
- this is for random order
- add a temp field with a random value
- sort by it
- unset the temp field
*i don't know if this is the optimal way to do it, but it works
aggregate(
[{"$set": {"rand": {"$rand": {}}}},
{"$sort": {"rand": 1}},
{"$unset": ["rand"]}])
Query2
- this in to apply a specific order for example "CD then AA etc"
- add a new field that contains the index of the
_id
from the array that defines the order - sort by it
- unset it
aggregate(
[{"$set": {"key": {"$indexOfArray": [["CD", "AA"], "$_id"]}}},
{"$sort": {"key": 1}},
{"$unset": ["key"]}])
CodePudding user response:
Similar to Takis' answer.
{ '$addFields': {
'order': { '$indexOfArray': [ ['CD', 'AA', 'EF', 'BC'...], '$_id' ] }}},
{ '$sort': { 'order': 1 }}]