skip to Main Content

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’.

2

Answers


  1. Chosen as BEST ANSWER

    Similar to Takis' answer.

             { '$addFields': {
                'order': { '$indexOfArray': [ ['CD', 'AA', 'EF', 'BC'...], '$_id' ] }}},
             { '$sort': { 'order': 1 }}]
    

  2. 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

    Playmongo

    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

    Playmongo

    aggregate(
    [{"$set": {"key": {"$indexOfArray": [["CD", "AA"], "$_id"]}}},
     {"$sort": {"key": 1}},
     {"$unset": ["key"]}])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search