B Seven
B Seven

Reputation: 45941

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

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

Answers (2)

B Seven
B Seven

Reputation: 45941

Similar to Takis' answer.

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

Upvotes: 0

Takis
Takis

Reputation: 8705

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

Upvotes: 3

Related Questions