0

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,
  }
]

1 Answer 1

1

Using indexOfArray

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

Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.