How to guarantee order of original array in mongo aggregate lookup

Viewed 54

I have an Array of ObjectIds like this

// Post Schema
{
  _id: ObjectId('..'),
  categories: [ObjectId('...'),ObjectId('...'),ObjectId('...')...]
}


// Category Schema
{
  _id: ObjectId('..'),
  name: '...',
  ...
}

// query
Post.aggregate()
  .match({ _id: targetPostId })
  .lookup({
     from: 'categories',
     localField: 'categories',
     foreignField: '_id',
     as: 'categories',
  })

And when I ran the mongo query through aggregate lookup, I noticed that the order of that Array is different from the original.

How can I keep the order of the original Array when using lookup?

0 Answers
Related