Reputation: 45941
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'.
Upvotes: 1
Views: 31
Reputation: 45941
Similar to Takis' answer.
{ '$addFields': {
'order': { '$indexOfArray': [ ['CD', 'AA', 'EF', 'BC'...], '$_id' ] }}},
{ '$sort': { 'order': 1 }}]
Upvotes: 0
Reputation: 8705
Query1
*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
_id
from the array that defines the orderaggregate(
[{"$set": {"key": {"$indexOfArray": [["CD", "AA"], "$_id"]}}},
{"$sort": {"key": 1}},
{"$unset": ["key"]}])
Upvotes: 3