Home > OS >  How to sort strings in a arbitrary or given order in Mongo Aggregation Pipeline?
How to sort strings in a arbitrary or given order in Mongo Aggregation Pipeline?

Time:09-17

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

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"]}])

CodePudding user response:

Similar to Takis' answer.

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