vy.pham
vy.pham

Reputation: 611

MongoDB sort by Array order

let say I have documents

[
  {
    score : 3,
  },
  {
    score : 1,
  },
  {
    score : 2,
  }
]

and an array contain order of score

const array = [2,1,3]

How can I sort documents by order of array

expected result :

[
  {
    score : 2,
  },
  {
    score : 1,
  },
  {
    score : 3,
  }
]

Upvotes: 0

Views: 62

Answers (1)

Noel
Noel

Reputation: 10525

Using indexOfArray

db.collection.aggregate([
{
    $addFields: {
        "order": {
            $indexOfArray: [[2,1,3], "$score"]
        }
    }
},
{
    $sort: {
        "order": 1
    }
}
]);

Playground

Upvotes: 1

Related Questions