Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

92
Views
Mongodb sort Aggregation in same order ids was passed on filter

I would like to know if its possible to keep the current order of the result the same as it is passed in on the filtering.

So lets say we have an array of IDS:

var arrayValues = [1,3,2]

I would like to aggregate the values but keep the result same order as im passing in the above array.

 var result = Item.aggregate([{ $match: { _id: { $in: arrayValues } }}])

I would want the result in same order as the array values passed in as _id value.

Example Result :

result = [{ _id: 1 },{ _id: 3 },{ _id: 2 }]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use indexOfArray for this:

db.collection.aggregate([
  {$match: {_id: {$in: arrayValues}}},
  {$set: {index: {$indexOfArray: [arrayValues, "$_id"]}}},
  {$sort: {index: 1}},
  {$unset: "index"}
])

See how it works on the playground example

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!